ppolyzos
ppolyzos

Reputation: 7091

Why join() method returns different result than expected

As mentioned in w3schools join() method, joins all elements of an array into a string, and returns the string. So if you try the following:

console.log(new Array(6).join('a'));

I would expect to get: "aaaaaa" but instead I get:"aaaaa", that means one less.

Can someone explain me why is that happening?

Upvotes: 4

Views: 111

Answers (2)

JoshuaRogers
JoshuaRogers

Reputation: 405

Your array will start with six elements. Since you are joining with "a", the letter "a" will get added to the string between all of the elements.

If you had the two elements "Hello" and "World" in your array and joined with a hyphen, it would be joined "Hello-World". So, if you have an array of n values, it only has to be joined n-1.

Upvotes: 4

Patricia
Patricia

Reputation: 7802

it puts the a between each element of your array, not after each one, so 6 elements has 5 joiners.

on this fiddle you can see a bit more exactly what the join is doing: http://jsfiddle.net/YKhmp/

Upvotes: 13

Related Questions