today I find one strange code
const nums = [1, 2, 3]
console.log(nums[-1])
and I can see the log is undefined
. why in JavaScript, we can access the invalid index without throwing any error?
today I find one strange code
const nums = [1, 2, 3]
console.log(nums[-1])
and I can see the log is undefined
. why in JavaScript, we can access the invalid index without throwing any error?
JavaScript arrays are a class of objects, and array entries are object properties.
Arrays can have other property names, but non-negative integer numbers used to lookup or set array entries affect the array's length
property.
The length of an array is maintained as one more than the highest non-negative index value used to store an entry in an array, or a non-negative integer used to set the arrays length
property itself.
The reason undefined
is returned from looking up a[-1]
is that it hasn't been set. If you set it first, you get its value back:
var a = [];
a[-1] = "silly";
console.log(a[-1]);
Negative "indeces" are converted to a string and used as a property name. They don't affect the length
property. Because they will confuse anybody trying to maintain the code, avoid using negative indeces deliberately - nobody else does.
Because that is just a property-access to an undefined property. Negative "indices" will not become part of the array-behavior, but otherwise they have a string-form and thus can be used as property names on objects, which include arrays too.
(Arrays can have any kind of properties, and if a property happens to be index-like enough, that will become included in the array-behaviour)
var someObject={
"-1":-1,
"a":"a"
};
console.log(someObject[-1],someObject["a"],someObject[-2]);
var someArray=[1,2,3];
someArray["4"]=5;
someArray.b="b";
console.log(someArray.length,someArray,someArray["b"],someArray.c);
var someVariable;
console.log(someVariable);
undefined
is practically a default value for everything.