Home > OS >  How array of 2 has length 2?
How array of 2 has length 2?

Time:03-04

As it's common arrays in js if you put 3 elements in array it will has length 3 but if I make array with only number two, it has length 2 ?!

const myArry=new Array(2)
console.log(myArry.length) // 2

CodePudding user response:

new Array(2) means "make me an array with two empty slots". So yes, it has length 2.

You may be looking for const myArry = [2] which has length 1.

EDIT

Just for fun, if you really wanted to use constructor syntax instead of array literal syntax (the [2] part), you could do:

new Array(1).fill(2)

Which actually could make sense if both the length and the fill value were dynamic parameters.

  • Related