DEV Community

Discussion on: 10 JavaScript string methods you should know

Collapse
 
frugencefidel profile image
Frugence Fidel • Edited

They are not same

 const first = new Array(2).join('a');
 console.log(first); // 'a'

 const second = 'a'.repeat(2);
 console.log(second); // 'aa'

 // new Array(52).join('a') will not print 52 a's, print 51 a's
 const aLength = new Array(52).join('a').length;
 console.log(aLength); // 51
Collapse
 
itsasine profile image
ItsASine (Kayla) • Edited

Oops, you're right! Typo on my part :) For the sake of my E2E tests, I actually think repeat would be easier to read.

it('displays an error for too many characters', function() {
    relevantPage.middleInitial.sendKeys('a'.repeat(2)); // clearly shows that 2 is considered too many

    expect(relevantPage.middleInitialTooLongMessage.getText()).toEqual('Middle initial is too long');
});
Thread Thread
 
frugencefidel profile image
Frugence Fidel

Actually repeat is easy to read

If you want to make string of 52 a's with repeat is so easy

  const a = 'a'.repeat(52);
  console.log(a); // "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa"
  console.log(a.length); // 52
Thread Thread
 
siddharthray profile image
siddharthray

Array index starts from 0 which means it will print 52 times.

Thread Thread
 
diek profile image
diek

Yass, and since join acts as 'glue', using 'a' as glue for 52 nothings will print 'a' 51 times. Give it a try ;)