Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How length property of an array works in javascript?

In javascript is it possible to directly set length property of an array. For example I can shorten the array like this:

var arr = [1, 2, 3, 4];
arr.length = 2;
console.log(arr); // Array [ 1, 2 ]
// arr[2], arr[3] are deleted

I would expect the length to be read-only (e.g. as in java).

As I understand, array in javascript is also an object:

console.log(typeof [1, 2, 3]); // object

How the length property works under the hood?

like image 692
madox2 Avatar asked Jan 24 '16 14:01

madox2


1 Answers

The necessary steps to be fulfilled when length is being set on an Array is described on section 9.4.2.4 ArraySetLength of ES 6.0 language specification.

It deletes index properties from the old length of the array to the new length of the array according to step 19:

While newLen < oldLen repeat,    
    Set oldLen to oldLen – 1.
    Let deleteSucceeded be A.[[Delete]](ToString(oldLen)).
    Assert: deleteSucceeded is not an abrupt completion.
    If deleteSucceeded is false, then
        Set newLenDesc.[[Value]] to oldLen + 1.
        If newWritable is false, set newLenDesc.[[Writable]] to false.
        Let succeeded be OrdinaryDefineOwnProperty(A, "length", newLenDesc).
        Assert: succeeded is not an abrupt completion.
        Return false.

Whenever you set up a property for the array, it checks first to see if the property is length and if it is, it's supposed to do the ArraySetLength operation. This operation is described in section 9.4.2.1 [[DefineOwnProperty]] (this for Array Exotic Objects).

When the [[DefineOwnProperty]] internal method of an Array exotic object A is called with property key P, and Property Descriptor Desc the following steps are taken:

Assert: IsPropertyKey(P) is true.
If P is "length", then
    Return ArraySetLength(A, Desc).

If it's not length and it's an indexed property the other steps in the operation are performed. Basically sets the value of the length property to the value of the index property + 1. As far as I can tell, the ArraySetLength operation isn't being used here to set the new length of the array.

like image 53
MinusFour Avatar answered Oct 27 '22 00:10

MinusFour