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:

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

Leave a Reply