skip to Main Content

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


  1. 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 into copyItem with each iteration, each line of output shows one more item than the one before it.

    Login or Signup to reply.
  2. 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
    
    
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search