Javascript: length doesn't work on arrays that are inside an object?-Collection of common programming errors

The main problem is that in javascript data declaration like your first example, the value of this is not set to the object being defined. So since this is not your object, this.a inside the object declaration does not refer to the a property of your object.

It is whatever it was in the context right before your data declaration. If that was the global context, then this would be the window object and this.a probably doesn’t exist. If it doesn’t exist (e.g. it’s undefined), then when you try to reference this.a.length, you are trying to read the property .length off something isn’t an object and that is a javscript error.

As for solving this problem it is generally a bad idea to copy the length of an array to another property. That just gives you a chance for it to be wrong and out-of-sync with the actual length of the array. If you want the length of the array, you should just retrieve it upon demand with:

object.a.length

If you really want it to be a property (that has a fixed value and doesn’t change when a changes), you can set it after you create the object:

var object = {
   a:[1,2,3,2],
};
object.b = object.a.length;
alert(object.b);

Originally posted 2013-11-09 23:15:21.