Reputation: 322
What is the reason behind the length of string
produced by joining var arr = [,,]
, like so: var str = arr.join(' ')
being one less than length of arr
.
var literal_arr = [,,],
joined_literal_arr = literal_arr.join(' '),
constructor_arr = new Array(2),
joined_constructor_arr = new Array(2).join(' ');
console.log("Literal array notation length = ", literal_arr.length);
console.log("Joined literal array notation string length = ", joined_literal_arr.length);
console.log("Constructor array notation length = ", constructor_arr.length);
console.log("Joined constructor notation string length = ", joined_constructor_arr.length);
Upvotes: 1
Views: 1046
Reputation: 367
It is simple as .join
will join array elements with separator
provided as argument. It won’t append separator
after the last element or prepend it before the first element. It will place separator
between elements only.
Upvotes: 0
Reputation: 115232
As per MDN docs :
If an element is undefined or null, it is converted to the empty string.
In your case, you are creating an array with a particular length without any value(it would be undefined
). So while joining there will be length - 1
separators(since undefined
already treated as an empty string) means length - 1
spaces(' '
).
Upvotes: 5