# 2 Ways to Repeat Strings

2 ways to repeat strings in JavaScript πŸŽ‰ I’ve always used β€œArray.fill” to do any repetitions. β€œrepeat” is a recent discovery 🀩

const canada = 'πŸ‡¨πŸ‡¦';

// Repeat method
canada.repeat(3);

// Fill method
Array(3)
  .fill(canada)
  .join('');

// result
('πŸ‡¨πŸ‡¦πŸ‡¨πŸ‡¦πŸ‡¨πŸ‡¦');

# How repeat works

The repeat method simply repeats your string. It returns a new string that concatentates the specified number of copies you indicated.

'πŸ‡¨πŸ‡¦'.repeat(3); // 'πŸ‡¨πŸ‡¦πŸ‡¨πŸ‡¦πŸ‡¨πŸ‡¦'

'Hey'.repeat(2); // 'HeyHeyHey'

'Blank'.repeat(0); // ''

# How fill works

// Step 1: Create an new array with 3 empty items
Array(3)
  // Step 2: Fill each empty slot with 'πŸ‡¨πŸ‡¦'
  .fill('πŸ‡¨πŸ‡¦')

  // Step 3: Join all the elements into a string
  .join('');

# Community Examples

# Using for loop

A classic example of repeating strings using the for loop πŸ‘

const canada = 'πŸ‡¨πŸ‡¦';
const arr = [];

for (let i = 1; i <= 3; i++) {
  arr.push(canada);
}

arr.join(''); // 'πŸ‡¨πŸ‡¦πŸ‡¨πŸ‡¦πŸ‡¨πŸ‡¦'

Thanks: Alen H.

# Using join only

A even shorter shortcut to repeat string using just the join method. Cool ✌️

Array(4).join('πŸ‡¨πŸ‡¦');

// returns 'πŸ‡¨πŸ‡¦πŸ‡¨πŸ‡¦πŸ‡¨πŸ‡¦'

Thanks: Diogo D.

# Using Array.from

This is an interesting example

Array.from({ length: 3 }, () => 'πŸ‡¨πŸ‡¦').join('');

// returns 'πŸ‡¨πŸ‡¦πŸ‡¨πŸ‡¦πŸ‡¨πŸ‡¦'

Thanks: @oliverturner

# ☝️ How that works?

Let me break down Oliver's example and explain it a bit more.

1.

The length property of the from() method is 1. So we set the length property to 3, which initializes the array with 3 corresponding undefined in each position.

Array.from({ length: 3 });

// returns [undefined, undefined, undefined]

2.

Now we utilize the 2nd parameter, which is a map function that will make a call on every element of the array. Here we are replacing all the undefined with 'πŸ‡¨πŸ‡¦'. Notice I've split this into two lines with {}, hence I need to use a return.

Array.from({ length: 3 }, () => {
  return 'πŸ‡¨πŸ‡¦';
});

// returns ['πŸ‡¨πŸ‡¦', 'πŸ‡¨πŸ‡¦', 'πŸ‡¨πŸ‡¦']

3.

Finally we call join() to combine all the elements in the array into a string.

Array.from({ length: 3 }, () => {
  return 'πŸ‡¨πŸ‡¦';
}).join('');

// returns 'πŸ‡¨πŸ‡¦πŸ‡¨πŸ‡¦πŸ‡¨πŸ‡¦'

# Resources


Related Tidbits