shubhamagiwal92
shubhamagiwal92

Reputation: 1432

Array method and join function combined output in javascript unable to understand

I defined myArr variable in javascript as follows:

var myArr= Array(3);

When I consoled the value of myArr it gave the following output:

[undefined × 3]

When I used the javascript join function which is as follows:

myArr.join('X');

And consoled the output I got the following:

"XX"

Can somebody explain me why I got this output? I was expecting the output to be

"undefinedXundefinedX"

Upvotes: 0

Views: 41

Answers (3)

Dhananjaya Kuppu
Dhananjaya Kuppu

Reputation: 1322

Array.prototype.join will perform the string conversions of all array elements and joined into one string. If an element is undefined or null, it is converted to the empty string. join

All the undefined elements are equal to ["", "", ""].join('X')

Upvotes: 1

Leo
Leo

Reputation: 13838

Array(3) creates an array of three empty holes.

To achieve your desired result, you need to fill the holes: Array(3).fill()

Upvotes: 1

brk
brk

Reputation: 50291

Array(3) will create an array of length 3.

On consoling myArr it will log empty array

join will join all elements of the array into a string

Upvotes: 0

Related Questions