Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why join() method returns different result than expected

Tags:

javascript

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?

like image 890
ppolyzos Avatar asked Dec 04 '22 08:12

ppolyzos


2 Answers

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/

like image 93
Patricia Avatar answered Dec 23 '22 11:12

Patricia


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.

like image 44
JoshuaRogers Avatar answered Dec 23 '22 11:12

JoshuaRogers