0

Why is the array returning it as if all of the array.shift()'s were performed first, then the console.log()'s?

Here is my code:

var y = [1,2,3,4,5,6];
y.shift();
console.log(y);
y.shift();
console.log(y);
y.shift();
console.log(y);

I would expect this to be the output:

[2,3,4,5,6]
[3,4,5,6]
[4,5,6]

But this is what I am currently getting:

[4,5,6]
[4,5,6]
[4,5,6]

Any idea what is going on here?

  • 2
    See also: [Is Chrome's JavaScript console lazy about evaluating arrays?](https://stackoverflow.com/q/4057440/5923139) – Aplet123 Jan 02 '21 at 17:45
  • I am running this within the script section of an HTML file using Electron if that is somehow relevant, since this doesn't seem to be happening when running this in "Tryit Editor". – John Traylor Jan 02 '21 at 17:45
  • Read the answers on the linked questions; `console.log` in the browser console evaluates the array lazily, which means only the final value is shown. – Aplet123 Jan 02 '21 at 17:47
  • 1
    Pretty sure @Aplet123's link is the answer. Running this code in my browser's dev tools section shows it correctly. If you want to be sure, toss in a `debugger;` before the first `y.shift()` and then step through it to verify that the shift function is working correctly – Jake Boomgaarden Jan 02 '21 at 17:47
  • @Aplet123 That certainly answers the question on why it is being printed that way. Unfortunately I was hoping that was the issue I was running into on a larger problem, evidently not. Thank you very much for your help. – John Traylor Jan 02 '21 at 17:50

0 Answers0