Javascript changes value when pushing an object



Have you ever encounter a problem in Javascript where it changes the value of the object when you push it to an array. Well, if you haven’t then maybe you’re not doing a lot of javascript.

Anyway, this particular issue is not really a bug, in fact this is a feature, an annoying feature if you don’t know how to fix it yet.

So here is a sample code below which I encourage you to try and run it yourself.

var a = [], b = {};
for(var i = 0; i < 3; i++) {
    b['text'] = 'Index is ' + i;
    a.push(b);
}

console.log(a)

If you try to run the above code, the output would be:

[
{"text" : "Index is 2"},
{"text" : "Index is 2"},
{"text" : "Index is 2"}
]

If you try to debug it and put console.log(b) before the push function, you will notice that the value of the object is right, but then the value changes when you push the object to the array a.

This is really what happens, when you push an object to a variable, you don't really push the actual object, you are just pushing a reference of that object. Since, in our example, we are pushing it inside a loop, the actual object will be pushed after the loop is done, in this case the value of the variable i will be 2. That's why the value of every object being pushed is {"text" : "Index is 2"}.

How to solve it

It's really very simple. Make sure you are not pushing the object itself. Instead push the actual value or create a new object every time the loop executes like the sample code below.

var a = [];
for(var i = 0; i < 3; i++) {
    var b = {};
    b['text'] = 'Index is ' + i;
    a.push(b);
}

console.log(a)