2

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?

1
  • 1
    The output is abcabcabc (so abc 3x times) - which is expected, because your passing in 3 Commented Jan 30, 2023 at 15:03

3 Answers 3

5

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

Sign up to request clarification or add additional context in comments.

Comments

1

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

1 Comment

Instead of simply providing the answer directly, try writing a detailed comment that explains the solution, as long as the explanation is not too lengthy
0

If you will have a look into the Array#join documentation, It will join the array items based on the passed separator in the join method. Ideally, It will not consider the join before the first and after the last element in an array.

console.log(Array(3)) // [undefined, undefined, undefined]

console.log([undefined, undefined, undefined].join('abc')); // 'abcabc'

As you want to fill the array with the string, Correct method is Array#fill which changes all elements in an array to a static value, from a start index (default 0) to an end index (default array.length) and then join the elements from an array with the help of Array.join() method.

console.log(Array(3).fill('abc').join(''));

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.