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' ]
*/