var dd = [];
const ff = { };
ff.dd = 0;
dd.push(ff);
console.log(dd);
ff.dd = 1;
dd.push(ff);
console.log(dd);
I am getting output
[ { dd: 0 } ]
[ { dd: 1 }, { dd: 1 } ]
but I want the output to be like
[ { dd: 0 } ]
[ { dd: 0 }, { dd: 1 } ]
To get that output, you'd have to create a new object (ff), instead of modifying the existing one.
var dd = [];
let ff = { }; // <== `let` instead of `const`
ff.dd = 0;
dd.push(ff);
console.log(dd);
ff = { }; // <== Create a new object
ff.dd = 1;
dd.push(ff);
console.log(dd);
Side note: You don't need ff at all:
var dd = [];
dd.push({dd: 0});
dd.push({dd: 1});
console.log(dd);
...and in fact the whole thing can be done in one initializer:
var dd = [
{dd: 0},
{dd: 1}
];
console.log(dd);
dd properties).Javascript keeps references to objects.
In your code, you initially push the ff variable with dd set to 0.
Then you modify the dd value of the same ff variable and push another reference to it into the array.
That is why you get an array with 2 references to the same ff object with dd value of 1.
If you want to achieve the result you wrote you need to create a new object before pushing it again into the array.
If your ff always is of one level deep, you can use Object.assign to clone ff each time you put it into the array.
var ffCopy = Object.assign({}, ff);
var dd = [];
const ff = { };
ff.dd = 0;
dd.push(Object.assign({}, ff));
console.log(dd);
ff.dd = 1;
dd.push(Object.assign({}, ff));
console.log(dd);
dd) for two entirely different things when asking questions, it makes both the question and its potential answers unnecessarily complicated.