Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How array of 2 has length 2?

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

>Solution :

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading