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?

4
  • 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 Commented Feb 5, 2020 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. Commented Feb 5, 2020 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" Commented Feb 5, 2020 at 21:12
  • @knot22 yea, util is a node package. Commented Feb 5, 2020 at 21:14

1 Answer 1

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.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.