Reputation: 2768
Here is a simplified version of an array of objects that I'm dealing with in a project -
let test = [];
test['12/1/2019'] = {k1: 25, k2: 'hello'};
test['1/1/2020'] = {k1: 14, k2: 'bonjour'};
console.log(test);
test['12/1/2019'] = {k1: 16, k2: 'ciao'};
test['1/1/2020'] = {k1: 10, k2: 'good day'};
I expected the console output to show this, on account of the console.log(test);
being before the lines of code that overwrite the original values:
However, the actual console output is this:
Why is it behaving this way?
Upvotes: 2
Views: 41
Reputation: 9149
This is because JavaScript engine runs every code in batches.
From the code, it looks like console.log
is called before setting the new values to the array, but in reality, all commands in the current iteration are run first before console.log
is run in the next iteration.
And because test
is a reference to a memory location for storing values for test
array, it now represents the updated value.
The same applies to objects as well.
Upvotes: 2