1

Can someone explain what's going on with the output of this code?

let arr = [];

for(let i=0; i < 5; i++){
  arr.push(i);
  console.log(arr, i)
}

Output:

[0, 1, 2, 3, 4] 0
[0, 1, 2, 3, 4] 1
[0, 1, 2, 3, 4] 2
[0, 1, 2, 3, 4] 3
[0, 1, 2, 3, 4] 4

I'd expect it to look like:

[0] 0
[0, 1] 1
[0, 1, 2] 2
[0, 1, 2, 3] 3
[0, 1, 2, 3, 4] 4
cory0s
  • 11
  • 1
  • 2
    What console is this, a browser? Some browser consoles save the array pointer, not the contents at the time you log it, so that you can look at the array in the console with the > button – user253751 Feb 25 '23 at 03:28
  • You can always force the current state to be shown with `JSON.stringify`: `console.log(JSON.stringify(arr), i)` – Unmitigated Feb 25 '23 at 03:30
  • Possibly: https://stackoverflow.com/questions/4057440/is-chrome-s-javascript-console-lazy-about-evaluating-objects – Andy Feb 25 '23 at 03:31
  • console.log behaviour is not standardized, and while the call itself should resolve synchrnously, the actualy _data writing_ tends to be asynchronous and non-blocking. So by the time the actual data write happens, the content of your array may no longer be what it was when you called `console.log`. _Always_ console.log `array.slice()` if exact content-at-that-moment matters. – Mike 'Pomax' Kamermans Feb 25 '23 at 03:44

1 Answers1

0

because your console is highly referential (everything in javascript including arrays (-undefined) is object and it is reference)

in chrome devtools 106 this works as expected

you can try a few tricks to create new arrays like:

let arr = [];

for(let i=0; i < 5; i++){
  arr.push(i);
  console.log(arr.slice(0), i)
}

anyway, referencing the output of devtools comes from its own source code with the task execution order. i tried eruda2 and it's the same as your devtools

Tachibana Shin
  • 2,605
  • 1
  • 5
  • 9