Why would “cookie” be pushed to both lines of arrays instead of just the bottom one?
Example: (5) ["banana", "apple", "peach", "pear", "cookie"]
(5) ["banana", "apple", "peach", "pear", "cookie"]
Repl link:
const groceries = ['banana','apple','peach','pear']
console.log(groceries)
// grab the 2rd index
//console.log(groceries[2])
// Array Methods
groceries.push('cookie')
console.log(groceries)
It isn’t, the program (Node.js right) is executed top-to-bottom. This means that cookie won’t be added to the array until after the array is printed. I tested it, here was my output:
If you run that in your browser’s dev tools, you should get the output you expect. Replit’s dev tools are a little slow, and JavaScript passes objects and arrays by reference, so likely the array is being changed before Replit’s dev tools have actually managed to log the array in the console hence the same value gets logged twice.
I think you are having the same problem as in this post. The array is changing values before it is logged, and the log function only has a reference, not a copy of the variable.
No, console.log is synchronous so that isn’t correct. You can prove that by pasting the code the poster provided in your browser console; you get the expected output rather than two of the same arrays.
If you are using the Replit virtual web view to run JavaScript, you have to go to settings and turn off Asynchronous Rendering. Then it will show up correctly. Most virtual JavaScript consoles that run inside a webpage are programmed using this rendering method as it optimizes performance better. The side effect of this optimization is that array changes won’t update correctly in console.
I made another attempt and got the same results as last time. Why am I not getting the results of this pushed item to one single line? It keeps going to all lists of arrays from top to bottom.