Skip to content Skip to sidebar Skip to footer

Array Length And Undefined Indexes

I just want to understand how Javascript arrays work but I have a complicated problem here. First I created my array: var arr = []; And set some elements in it: arr[5] = 'a thing'

Solution 1:

Note: Array indexes are nothing but properties of Array objects.

Quoting MDN's Relationship between length and numerical properties section,

When setting a property on a JavaScript array when the property is a valid array index and that index is outside the current bounds of the array, the engine will update the array's length property accordingly.

Quoting ECMA Script 5 Specification of Array Objects,

whenever a property is added whose name is an array index, the length property is changed, if necessary, to be one more than the numeric value of that array index; and whenever the length property is changed, every property whose name is an array index whose value is not smaller than the new length is automatically deleted

So, when you set a value at index 5, JavaScript engine adjusts the length of the Array to 6.


Quoting ECMA Script 5 Specification of Array Objects,

A property name P (in the form of a String value) is an array index if and only if ToString(ToUint32(P)) is equal to P and ToUint32(P) is not equal to 2−1.

So, in your case 2 and 4 are valid indexes but only 2 is defined in the array. You can confirm that like this

arr.hasOwnProperty(2)

The other indexes are not defined in the array yet. So, your array object is called a sparse array object.

So why arr[2] is counted in for..in loop and not arr[4] is not counted?

The for..in enumerates all the valid enumerable properties of the object. In your case, since only 2 is a valid property in the array, it will be counted.

But, when you print arr[4], it prints undefined, because JavaScript will return undefined, if you try to access a property which is not defined in an object. For example,

console.log({}['name']);
// undefined

Similarly, since 4 is not yet defined in the arr, undefined is returned.


While we are on this subject, you might want to read these answers as well,

Solution 2:

There’s a difference between a property that has the value undefined and a property that doesn’t exist, illustrated here using the in operator:

var obj = {
    one: undefined
};

console.log(obj.one === undefined); // trueconsole.log(obj.two === undefined); // trueconsole.log('one'in obj); // trueconsole.log('two'in obj); // false

When you try to get the value of a property that doesn’t exist, you still get undefined, but that doesn’t make it exist.

Finally, to explain the behaviour you see: a for in loop will only loop over keys where that key is in the object (and is enumerable).

length, meanwhile, is just adjusted to be one more than whatever index you assign if that index is greater than or equal to the current length.

Solution 3:

To remove undefined values from array , try utilizing .filter()

var arr = [];
arr[5] = "a thing";
arr[2] = undefined;
arr = arr.filter(Boolean);
document.write(arr.length);

Solution 4:

It all comes down the idea of how space is handled by machines. Let's start with the simplest idea of:

var arr =[];

This in turn creates a location where you can now store information. As @Mike 'Pomax' Kamermans pointed out: This location is a special javascript object that in turn functions as a collection of keys and values, like so:

arr[key] = value;

Now moving on through your code:

arr[5] = "a thing";

The machine now is understanding that you are creating something in the (giving value to the) 6th position/5th key (as array's first position is 0). So you wind up with something that looks like this:

arr[,,,,,"a thing"];

Those commas represent empty positions (elisions as @RobG pointed out) in your array.

Same thing happens when you declare:

arr[2] = undefined;
arr[,,undefined,,,"a thing"];

So when you're iterating inside an array using "for var in" you're checking for each one of the spaces in this array that are populated, so in turn 2.

As a difference, when you check for the length of the array, you're looking to see how many spaces to store information exist inside the array, which in turn is 6.

Finally, javascript interprets empty room in an array as unidentified values, which is the reason arr[4] is being outputted as such.

Hope that answered your question.

Solution 5:

JavaScript arrays, at least in the first version, were plain object with a length property. Most of the weird behaviour you experienced is a consequence of this.

Result interesting, it is 6. But it must contain two data, how its size can be 6? It is probably related with the latest index that I used here arr[5] = "a thing";

It results in 6 because the length is always 1 higher than the highest index, even if there are actually fewer items in the array.

o why arr[2] is counted in for..in loop and not arr[4] is not counted?

because when you are doing:

arr[2] = undefined;

You are actually adding a key called 2 to the array object. As result, the value arr[2] is counted in the for in loop, while the a[4] is ignored.

Post a Comment for "Array Length And Undefined Indexes"