Bala
Bala

Reputation: 11254

Why is this Array and join is always N-1?

When using Array with join it always returns N-1 elements. Here is what I mean. In javascript console I do the below.

    Array(2).join('*')  #=> "*"  but I was expecting "**"
new Array(1).join('*')  #=> ""   but I was expecting "*"

Am I missing something?

Upvotes: 2

Views: 76

Answers (2)

Leo
Leo

Reputation: 13848

Array(3) will create an array of 3 undefined members: [undefined, undefined, undefined], in which there are only 2 gaps, that's why .join('*') gives you '**'

Upvotes: 0

spender
spender

Reputation: 120490

Join inserts strings between elements. So, how many "between" positions are there with N elements? Yes... N-1

Upvotes: 6

Related Questions