Skip to content
Advertisement

Why [,,].join(‘ ‘) length is one less than array length?

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); 

Advertisement

Answer

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(' ').

User contributions licensed under: CC BY-SA
6 People found this is helpful
Advertisement