0

Javascript, when pushing outside-defined object into array in a for loop, the last one is repeatedly pushed.

I read many Q/A (see below links) and know the solution, but did not find explanation for the follwing 2 points:

  1. before and after the push, console.log the obj, it shows properly all objects (not repeating the last one), but push works only the last one;

  2. If object defined outside is "always the same object", why not repeat the first one, but repeat the last one?

Related Q/A:

How to push object to array from for loop properly in JavaScript?

React push object into array, always pushed last array

After pushing objects into array, every object in the array has the same value

let arr = [];
let obj = {};

for(let i=0; i<5; i++) {
  obj["single"] = i;
  obj["double"] = i*2;
  console.log(obj);
  arr.push(obj);
}

console.log(arr);

result:

{ single: 0, double: 0 }
{ single: 1, double: 2 }   
{ single: 2, double: 4 }   
{ single: 3, double: 6 }   
{ single: 4, double: 8 }   

[
  { single: 4, double: 8 },
  { single: 4, double: 8 },
  { single: 4, double: 8 },
  { single: 4, double: 8 },
  { single: 4, double: 8 } 
]     
weix
  • 1
  • 5
  • Create a new object each time, instead of mutating and push the same object - `arr.push({ single: i, double: i * 2 });`. – Ori Drori Feb 24 '21 at 21:17
  • Thanks, I know the solution. but cannot understand the reason. – weix Feb 24 '21 at 21:18
  • You have a single object, and you have an array with 5 slots, that each of them points at the same object. Whenever you change the object, all the slots show the same values, because they reference the same object. Try `console.log(arr[0] === arr[1])`, and you'll get `true`, and them same thing would happen for any pair combination. – Ori Drori Feb 24 '21 at 21:22
  • thanks, I think I understand. the array stored a pointer to the obj. the value of the obj is continuously updated. right? – weix Feb 24 '21 at 21:28
  • Yep. You mutate the same object all the time, so all slots show the last update. – Ori Drori Feb 24 '21 at 21:31

0 Answers0