Home > Software engineering >  When executing this code, instead of moving all items from 'myList' to 'myCart'
When executing this code, instead of moving all items from 'myList' to 'myCart'

Time:11-10

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-

CodePudding user response:

Try this

let myList = ['pop tarts', 'ramen', 'chips', 'salsa', 'coffee']
let myCart = Array.from(myList);
myList  = []
console.log(myList)
console.log(myCart)

CodePudding user response:

The behaviour is expected because you are iterating over the array and in the same time you are modifying it.

  • Step 0 : item = 'pop tarts', 'coffee' is removed, myList = ['pop tarts', 'ramen', 'chips', 'salsa']
  • Step 1 : item = 'ramen', 'salsa' is removed, myList = ['pop tarts', 'ramen', 'chips']
  • Step 2 : item = 'chips', 'chips' is removed, myList = ['pop tarts', 'ramen']

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.

  • Related