Ann Pavlov
Ann Pavlov

Reputation: 150

Why new Array(256).join(' ') returns 255 white spaces?

let white = new Array(256).join(' ')

console.log(white)

Why the following snippet returns string with 255 white spaces? Why not 256?

Upvotes: 1

Views: 376

Answers (4)

Kas Elvirov
Kas Elvirov

Reputation: 7980

Because of the relationship BETWEEN spaces and the number of characters. You're adding whitespaces not before or after elements in the array.

let white = new Array(n).join(s); // s = n - 1

picture

let string = "One two three four five"; // 5 elements
let spaces = string.split(" ").length - 1;
console.log(spaces); // returns 4

Upvotes: 3

LeGEC
LeGEC

Reputation: 51932

As stated in other answers : .join(' ') will add the ' ' between array elements, and will be repeated only n-1 times.


If your intention is to have a 256 long line of spaces, use the String.repeat() method :

let white = ' '.repeat(256)

Upvotes: 0

Suren Srapyan
Suren Srapyan

Reputation: 68665

Because if your array has 2 elements, only 1 gap is between them, so joining them will always result length - 1.

Example with more obvious | characters. We have 3 empty strings and joining them will return only 2 pipes.

const array = ['', '', ''];

console.log(array.join('|'));

Upvotes: 4

str
str

Reputation: 44979

You create an array consisting of 256 elements. join(' ') will join them to a string by adding a whitespace in between the elements (but not before the first or after the last).

Upvotes: 2

Related Questions