Search code examples
javascriptfor-loopforeach

Can someone please explain the behavious of the console.log() within the for loop below


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

*/


Solution

  • 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:

    // first loop
    // you add the first item 'Books' to the copyItem array
    copyItem: ['Books']
    console.log(copyItem)
    
    // second loop
    // you add the second item 'Pens' to the copyItem array
    copyItem: ['Books', 'Pens']
    console.log(copyItem)
    
    
    // this then loops for the entirety of the array