5

You know that in Javascript you can access the length of an text/array with length property:

var obj = ["Robert", "Smith", "John", "Mary", "Susan"];

// obj.length returns 5;

I want to know how this is implemented. Does Javascript calculates the length property when it is called? Or it is just a static property which is changed whenever the array is changed. My question is asked due to the following confusion in best-practices with javascript:

for(var i = 0; i < obj.length; i++)
{

}

My Problem: If it is a static property, then accessing the length property in each iteration is nothing to be concerned, but if it is calculated on each iteration, then it cost some memory.

I have read the following definition given by ECMAScript but it doesn't give any clue on how it is implemented. I'm afraid it might give a whole instance of array with the length property calculated in run-time, that if turns out to be true, then the above for() is dangerous to memory and instead the following should be used:

var count = obj.length;
for(var i = 0; i < count; i++)
{

}
6
  • 5
    It is not recalculated when referenced, it is set when something happens to change the length of the array. People have been writing for (var i=0; i<obj.length; i++) for decades with no "danger to memory". Retrieving length in advance and assigning it to a variable like count is merely a micro-optimization that saves one property reference each time through the loop.
    – user663031
    Commented Nov 15, 2014 at 8:10
  • 1
    Also, do note that different implementations of JavaScript may have subtly different behavior. In the case of .length, they probably all work how @torazaburo said above, but a precise explanation will be based on the platform.
    – Cel Skeggs
    Commented Nov 15, 2014 at 8:18
  • @Mostafa: obj.length is 5.
    – Aravind
    Commented Nov 15, 2014 at 8:31
  • @Mostafa: Okay, the length is a static property of array, which gets auto updated when you alter it's elements. However, there are a few things to note
    – Aravind
    Commented Nov 15, 2014 at 8:55
  • 1
    you can run a cpu profiler in chrome for javascript to see what it calls behind ...anyway while is faster than for in most browsers
    – HellBaby
    Commented Nov 15, 2014 at 10:30

3 Answers 3

5

Array in JavaScript is not a real Array type but it's an real Object type.

[].length is not being recalculated every time, it is being operated by ++ or -- operators.

See below example which is behaving same like array.length property.

var ArrayLike = {
    length: 0,
    push: function(val){
        this[this.length] = val;
        this.length++;
    },
    pop: function(){
        delete this[this.length-1];
        this.length--;
    },
    display: function(){
        for(var i = 0; i < this.length; i++){
            console.log(this[i]);
        }
    }
}

// output
ArrayLike.length // length == 0
ArrayLike.push('value1') // length == 1
ArrayLike.push('value2') // length == 2
ArrayLike.push('value3') // length == 3
ArrayLike.pop() // length == 2
ArrayLike.length === 2 // true
5
  • What's a "real Array type"? What a real array is is a matter of perspective only. Commented Nov 15, 2014 at 10:46
  • but same implementation is also in c# ...you say that array isn't array after all in all languages(do you think when you speak?)
    – HellBaby
    Commented Nov 15, 2014 at 11:09
  • @yerforkferchips: in JavaScript array constructor is inherited from Object constructor, like: var somevar = new Array(1, 2, 3, 4); Now we can use somevar variable to behave like object: somevar.prop1 = "test"; console.log(somevar.length) // 4 console.log(somevar.prop1) // test Commented Nov 15, 2014 at 11:22
  • @HellBaby: we can have static properties in JS array like: somevar.prop1 = "some value", plus JavaScript array does not have a special syntax for creating multidimensional arrays Commented Nov 15, 2014 at 11:37
  • Being an Object/having Object in its prototype chain does not make it not an Array. Commented Nov 15, 2014 at 13:14
1
var a = ["abc","def"];

a["pqr"] = "hello";

What is a.length?

2

Why?

a.length is updated only when the index of the array is a numeric value. When you write

var a = ["abc","def"];

It is internally stored as:

a["0"] = "abc"

a["1"] = "def"

Note that the indexes are really keys which are strings.

Few more examples:

1.)

var a = ["abc","def"];

a["1001"] = "hello";

What is a.length?

1002

2.) Okay, let's try again:

var a = ["abc","def"];

a[1001] = "hello";

What is a.length?

1002

Note here, internally array is stored as

a["0"] = "abc"

a["1"] = "def"

a["1001"] = "hello"

3.) Okay, last one:

var a = ["abc"];

a["0"] = "hello";

What is a[0]?

   "hello"

What is a.length?

1

It's good to know what a.length actually means: Well now you know: a.length is one more than the last numerical key present in the array.

6
  • "Only if the index is a numeric value" is a bit misleading -- anything but numeric property names does not behave like indices for arrays, and you certainly won't have these properties come up in any typical loop over an array. Commented Nov 15, 2014 at 10:43
  • @yerforkferchips: It is true that the keys which are not numbers won't turn up in a for loop, but a for-in loop would show up. It is always good to know how the length property works, so it doesn't trip us.
    – Aravind
    Commented Nov 15, 2014 at 13:14
  • I'm not saying your answer is wrong, but I'm saying what you're showing in that specific example is not array indices, and does not act like them. Commented Nov 15, 2014 at 13:20
  • @yerforkferchips Yes, that is right, then again, there is no concept of indices in Javascript. Javascript Arrays are just customized objects, which try to act like a traditional array, providing a bunch of useful helper functions. They are just key-value pairs internally. While, one can use it strictly in the number index format, it is better to be aware of how it works.
    – Aravind
    Commented Nov 15, 2014 at 13:31
  • 1
    @yerforkferchips: Thanks, The spec says so. I didn't know that.
    – Aravind
    Commented Nov 15, 2014 at 13:39
0

I want to know how this is implemented. Does Javascript calculates the length property when it is called? Or it is just a static property which is changed whenever the array is changed.

Actually, your question cannot be answered in general because all the ECMA specs say is this:

The length property of this Array object is a data property whose value is always numerically greater than the name of every deletable property whose name is an array index.

In other words, the specs define the invariant condition of the length property, but not it's implementation. This means that different JavaScript engines could, in principle, implement different behavior.

0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.