Home > Software engineering >  Unexpected Output from Array() Method
Unexpected Output from Array() Method

Time:01-31

I have this snippet of code below and don't quite understand the output

function repeatStringNumTimes(str, num) {
  if (num <0) {
    return ""
  } else {
  return Array(num 1).join(str)
  }
}

console.log(repeatStringNumTimes("abc", 3));

I would have expected the output to be "abcabcabc" though if I console.log(repeatStringNumTimes("abc", 3)) in JS Bin it produces "abcabc"?

If I specify Array(3) - Would it not concatenate the string 3 times? Why only 2 in this instance?

CodePudding user response:

If I specify Array(3) - Would it not concatenate the string 3 times? Why only 2 in this instance?

console.log([1,2,3].join('abc'))
// outputs 1abc2abc3

Note that 'abc' is the separator for the join between the 3 elements, and so it appears twice, not 3 times.

Therefore, if you create an empty array, it shows 'abc' twice, separating 3 empty strings:

console.log(Array(3).join('abc'))
// outputs abcabc

Also note that there is String.repeat()

console.log('abc'.repeat(3))
// outputs abcabcabc

CodePudding user response:

look when i run your code the right output appears so your code has no bugs, and when you specify Array(3) the output will be "abcabc" your code is working well

  • Related