Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

JavaScript push not working as expected, but a console log right before the push method shows exactly what I was expecting

When I run the following code, the console logs give me exactly what I want, but the end array of objects doesn’t which I really don’t understand..

function pickWinners(numbers) {  
    const winnerArr = [];
    const winnerObj = {};
    for(let i = 0; i < numbers.length; i++) {
        if(numbers[i] % 2 != 0 && i % 2 != 0) {
            winnerObj.seat = i;
            winnerObj.ticketCost = numbers[i];
            console.log(winnerObj);
            winnerArr.push(winnerObj);
        }
    }
    return winnerArr;
}

pickWinners([6, 7, 12, 49])

The console log gives me (as expected):

Object { seat: 1, ticketCost: 7 }   
Object { seat: 3, ticketCost: 49 }

But the returned array is:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

0: Object { seat: 3, ticketCost: 49 }  
1: Object { seat: 3, ticketCost: 49 }

Could someone please explain what is going on? Especially when the console log is executed just before the push.

Thanks in advance!

I was expecting the returned array to be the same result as what was printed with the console log

>Solution :

You need to define your winnerObj inside your for loop so it is block-scoped. This causes a new winnerObj to be created each time. The code you currently have is using the same winnerObj for each instance. And when you change winnerObj, it changes the instances that are already in the array, too.

If you still don’t understand, try reading this: https://dmitripavlutin.com/value-vs-reference-javascript/

function pickWinners(numbers) {
  const winnerArr = [];
  for(let i = 0; i < numbers.length; i++) {
    const winnerObj = {};
    if(numbers[i] % 2 != 0 && i % 2 != 0) {
      winnerObj.seat = i;
      winnerObj.ticketCost = numbers[i];
      console.log(winnerObj);
      winnerArr.push(winnerObj);
    }
  }
  return winnerArr;
}

console.log("overall:", pickWinners([6, 7, 12, 49]))
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading