The reason 2
does not have a length is because it's a number, not an array.
If you intended to find the length of a variable named testvar
, you should use testvar.length
. However, this will also be undefined as objects created with { ... }
notation do not have a length property.
In Javascript, only arrays have a length property:
var testvar = [ ];
testvar[1] = 2;
testvar[2] = 3;
alert(testvar.length); // 3
It's important to note that arrays in Javascript start indexing at 0
and can be sparse or non-sparse. This is why the result is 3 instead of 2. For more information on when arrays are sparse, refer to this article.