Reputation: 6305
Im updating a part of an object and the update works fine.Its when I did a console.log on the object before the I called the update functio,n the object was already updated.I was expecting to see the old copy of the object,i know Im doing something really silly.I just want to understand why this is happening.Here is my code
function updateObject(o){
o.a='oneHundred';
o.b='twoHundred'
}
var obj={
a : 'one',
b : 'two',
c : {
a : '',
b : ''
}
}
console.log(obj);//outputs the updated object before I call updateObject()
var upObject = obj.c ;
updateObject(upObject);
console.log(obj);
Upvotes: 1
Views: 130
Reputation: 32598
Chrome will display the object itself in the console, not a representation of the object at that point in time. You can call stringify
to get a snapshot and log that so it won't change when you change the object.
console.log(JSON.stringify(obj));
Upvotes: 2
Reputation: 22535
Chrome (and possibly firebug) doesn't actually log the current state of an object until you observe it. If you put a breakpoint in the code like so:
console.log(obj);//outputs the updated object before I call updateObject()
debugger; // force breakpoint
var upObject = obj.c ;
updateObject(upObject);
console.log(obj);
and then expand the object you will see that it's the un-updated version. You're better off logging the specific properties you want to see rather than entire objects when you can.
Upvotes: 3