Because 2
isn’t an array, it’s a number. Numbers have no length.
Perhaps you meant to write testvar.length
; this is also undefined, since objects (created using the { ... }
notation) do not have a length.
Only arrays have a length property:
var testvar = [ ];
testvar[1] = 2;
testvar[2] = 3;
alert(testvar.length); // 3
Note that Javascript arrays are indexed starting at 0
and are not necessarily sparse (hence why the result is 3 and not 2 — see this answer for an explanation of when the array will be sparse and when it won’t).