-1

Hoping someone can shed some light on this simple piece of code not working as expected:

var arr = new Array(10);
arr.length; // 10. Why? Very wierd.

Why does it return 10?

Uwe Keim
  • 39,551
  • 56
  • 175
  • 291
kea
  • 75
  • 9

4 Answers4

4

You instantiated the array with ten elements

Josh Withee
  • 9,922
  • 3
  • 44
  • 62
3

I makes an Array with 10 cells... so it returns 10 :)

You wanted to do:

var arr = [10]
Yoav Glazner
  • 7,936
  • 1
  • 19
  • 36
3

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array

If the only argument passed to the Array constructor is an integer between 0 and 232-1 (inclusive), this returns a new JavaScript array with its length property set to that number

So it is impossible to create a new array with only one number element using the new keyword.

You can however do :

var arr = [10]; // Creates a new array with one element (the number 10)
console.log(arr.length); // displays 1 because the array contains one element.
Sébastien
  • 11,860
  • 11
  • 58
  • 78
  • This is the right answer. The syntax is different depending on what you want to do, e.g. `var arr = new Array(arrayLength)` vs. `var arr = [item1, item2, etc]` – David Calhoun Dec 24 '17 at 17:43
1

It returns 10, because you give only one integer, as argument, to the Array constructor. In this case, the new Array constructor is acting like some programming languages where you needed to specify the memory for your array so you don't get those ArrayIndexOutOfBounds Exceptions. An example of this in Java:

int[] a = new int[10];

Or C#:

int[] array = new int[5];

In Javascript, when you write:

var a = new Array(10);
a[0] // returns undefined
a.length // returns 10.

and if you write:

a.toString() // returns ",,,,,,,,,", a comma for each element + 1

But, since Javascript doesn't need to allocate memory for an array, is better to use use the [] constructor:

var a = [10];
a[0] //returns 10
a.length //returns 1

I think that the thing that confuse all the people is this:

var a = new Array(1,2,3,4,5);
a[0] // returns 1
a.length // returns 5

But you can do the same in this way:

var a = [1,2,3,4,5];
a[0] // returns 1
a.length // returns 5

So, in conclusion, try to avoid using the new Array constructor, and use the [] constructor instead.

GuilloteL
  • 112
  • 1
  • 5