const arr = new Array(1);
arr[0] = {x: "first", y: "second"}
arr[0][5] = "third"
console.log(arr)
// Result: [{5: "third", x: "first", y: "second"}]
Why did it add 5: "third" in the beginning like that? How does JS handle this under the hood?
const arr = new Array(1);
arr[0] = {x: "first", y: "second"}
arr[0][5] = "third"
console.log(arr)
// Result: [{5: "third", x: "first", y: "second"}]
Why did it add 5: "third" in the beginning like that? How does JS handle this under the hood?
Well, arr[0]
is your object {x: "first", y: "second"}
.
So, when you do arr[0][5] = "third"
, you are saying to assign the value "third"
to the 5
property of that same object. So, then when you examine arr
, you see your original object you put there with the 5
property added to it.
You could also do it this way (in case this helps you understand it better):
const arr = new Array(1);
let z = {x: "first", y: "second"};
arr[0] = z; // assign z object into our array
z[5] = "third"; // add "5" property to the z object
console.log(arr); // now look at the z object in our array
In both my code example and your code example, you assign a pointer to your object to arr[0]
. Then, in your example, you get that pointer again and assign it a new value with
arr[0][5] = "third";
Or, in my example, I retain a pointer to that same object and assign it a new property that way. Both point to the same object.
And, using this syntax:
arr[0][5] = "third";
says to get the value of arr[0]
and then assign the 5
property of that a value of "third"
. Keep in mind that indexing with [5]
works for either array entries or for property values. If the object you are using the index assignment on is not an array (which is the case here), then Javascript tries to make a string out of the index value and assigns a property to the underlying object with that property name.
Why did trying to access a single dimensional array of objects as double array change the underlying object. Why did it add 5: "third" in the beginning like that? How does JS handle this under the hood?
Because the [5]
is not only array indexing, it's also property access. If the underlying object you are indexing on is an array, then that gets the 6th element of the array. If the underlying object you are indexing on is not an array (just a plain object), then that accesses the "5" property of the object.
It works through property accessors
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Property_accessors
Basically as you know arrays are accessed through indexes inside square brackets. In this case object properties are accessed and created through a similar thought process
Here is a summary from resource provided
One can think of an object as an associative array (a.k.a. map, dictionary, hash, lookup table). The keys in this array are the names of the object's properties.