I came across the forEach() method in one of my exercise work and I decided to read more about it. During my research, I came across an example of a for loop being converted to forEach() method. I found it amazing and I decided to tried it out.
I wrote the code below and I call the console.log() inside within the loop curly braces, instead of outside of the curly braces. To my outmost surprise, i got more arrays in the console to what I was not anticipating see
before
const items = ["Books", "Pens", "Inks", "Ram of Sheet"];
let copyItem = [];
for(const item of items){
copyItem.push(item)
}
console.log(copyItem);//[ 'Books', 'Pens', 'Inks', 'Ram of Sheet' ]
//after
items.forEach((elem)=>{
copyItem.push(elem)
})
This was my Surprise. I tried to assumed that the behavious was cause by looping through the items array, which I am not also sure of. Can someone please explain this loop better for my understanding?
const items = ["Books", "Pens", "Inks", "Ram of Sheet"];
let copyItem = [];
for(const item of items){
copyItem.push(item)
console.log(copyItem);//varify position of this console!!
}
/* console output
[ 'Books' ]
[ 'Books', 'Pens' ]
[ 'Books', 'Pens', 'Inks' ]
[ 'Books', 'Pens', 'Inks', 'Ram of Sheet' ]
*/
2
Answers
Your code iterates over an array of four items, calling
console.log
for each iteration. So you get four iterations and therefore four lines of output.Each line of output contains the state of the variable
copyItem
. Since your code pushes a new element intocopyItem
with each iteration, each line of output shows one more item than the one before it.the reason why you’re seeing multiple arrays printed is because you are console.log-ing the array to which you are pushing items. Every time you push an item you also call
console.log(copyItem)
on it, meaning it prints the state of the current array in that loop.So you could visualise it like this: