JavaScript: repeat()

·

2 min read

repeat() is one of those methods that's not essential to know, but if you do it, it does make things simpler.

Let's say you have a form which takes your first name and converts it to a username. The username has to be 8 characters long. If your name is longer than that it will just take the first 8 characters. If it's shorter, we add '0's.

My name is Nic, so my username will be Nic000000. You can easily do this with a for loop:

const name = 'Nic'
let username = name;
if (username.length < 8) {
  const difference = 8 - username.length;
  for (let i = 0; i < difference; i++) {
    username += '0';
  }
}

Let's do the same, but using repeat:

const name = 'Nic'
let username = name;
if (username.length < 8) {
  const difference = 8 - username.length;
  username += '0'.repeat(difference);
}

So in this case it hasn't saved us many lines of typing, but that's because this is is a simple (and unlikely) answer. It's just less work to write repeat() rather than a for loop.