list
is an array, which is an object. Standard arrays in JavaScript are objects, not the contiguous blocks of memory divided into fixed-size elements that they are in most programming languages. They have their own literal form, they inherit from Array.prototype
, and they have a length
property that adjusts itself if you increase their size (and that can remove entries if you assign to it), but other than that they're just objects. You can add non-entry properties to them, as you've discovered, because they're just objects.
Here's a simpler example:
const a = [];
a.example = "hi there";
console.log(a.example); // "hi there"
In fact, what you think of as array indexes are actually property names, and they're strings. Example:
const a = ["zero"];
for (const index in a) {
console.log(index + " (" + typeof index + ")");
}
A property name is considered an array index if it meets certain criteria:
An integer index is a String-valued property key that is a canonical numeric String (see 7.1.21) and whose numeric value is either +0 or a positive integer ≤ 253 - 1. An array index is an integer index whose numeric value i is in the range +0 ≤ i < 232 - 1.
We typically write them as numbers, and JavaScript engines optimize, but in specification terms they're strings. :-)
the list appears in brackets when i log it
Typically, when you log something with a console, the console looks at it to see what it is and then bases its output on that. With most consoles, when you log an array, they just log the array entries without showing you the other properties. (That's also what you get when you use JSON.stringify
, since JSON arrays can't have non-entry properties.) But the property is there, as you saw. You can also see it in for-in
loops, since for-in
loops through the properties of the object, not the entries of the array:
const list = [1, 2, 3];
Object.assign(list, {property: true});
for (const key in list) {
console.log(`${key} = ${list[key]}`);
}