2

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:
enter image description here

However, the actual console output is this:
enter image description here

Why is it behaving this way?

knot22
  • 2,648
  • 5
  • 31
  • 51
  • 1
    see that `i` icon in the console log? If you hover it, it will say to you that this log was evaluated at the moment, so it is showing the current value of `test`, not the value of when `.log()` was supposedly called – Calvin Nunes Feb 05 '20 at 21:01
  • What is this running on? If you do this in node and try something like console.log(util.inspect(test, { maxArrayLength: null })); you will see the issue doesn't occur. – Kyle Berezin Feb 05 '20 at 21:06
  • @KyleBerezin This is in Vue.js. I copied/pasted your code in and re-executed but got this error msg: [Vue Warn]: Error in created hook: "ReferenceError: util is not defined" – knot22 Feb 05 '20 at 21:12
  • @knot22 yea, util is a node package. – Kyle Berezin Feb 05 '20 at 21:14

1 Answers1

2

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.

technophyle
  • 7,972
  • 6
  • 29
  • 50