let myList = ['pop tarts', 'ramen', 'chips', 'salsa', 'coffee']
let myCart = []
myList.forEach((item) => {
let poppedItem = myList.pop()
myCart.push(poppedItem)
console.log(myList)
console.log(myCart)
})
// When executing this code, instead of moving all items from 'myList' to 'myCart' it's exiting after moving just 3 of the items. I am totally lost as to why-
Try this
let myList = ['pop tarts', 'ramen', 'chips', 'salsa', 'coffee']
let myCart = Array.from(myList);
myList = []
console.log(myList)
console.log(myCart)
The behaviour is expected because you are iterating over the array and in the same time you are modifying it.
You are already visited all the elements of the array so the forEach ends, for further informations you can check the mozilla documentation link I provided containing the modifying_the_array_during_iteration paragraph.