0

I've this code :

data["id"] = 0;                                                     
console.log(data); // first log
found["test"] = data;
delete data.id;
console.log(data); // second log

where data and found is objects created before.

My console print two times the data objects without the "id" properties.

If i replace the delete with : data.id = ''; the console print two times the data object with an empty id property.

Also the found["test"] has the object without the id ( or with id = "" depending which experiment I'm in )

Could someone help me understand what's happening ?

Brian Tompsett - 汤莱恩
  • 5,753
  • 72
  • 57
  • 129
E-3000
  • 37
  • 8
  • possible duplicate of [Is Chrome's JavaScript console lazy about evaluating arrays?](http://stackoverflow.com/questions/4057440/is-chromes-javascript-console-lazy-about-evaluating-arrays) – Felix Kling Dec 13 '13 at 20:25
  • I was indeed using Chrome, but firefox give me the exact same result :( – E-3000 Dec 13 '13 at 20:29
  • @d.zOid: It's because both consoles will only evaluate the object once you expand it, not before. And by that time, it's already been deleted. Try to `console.log(JSON.stringify(data))` instead. – gen_Eric Dec 13 '13 at 20:30

1 Answers1

4

The console.log is playing tricks on you. The variable data is unchanged. The object referenced by the variable data is what's changing. Your log will show the state of the obejct when you click on it, not when it's logged.

It's not that the delete is happening early, it's that your browser console is opening the object up too late.

If you insert a debugger statement to pause execution, you should see what you expect to see. Then continue execution, and the property will get deleted as you expect.

data["id"] = 0;                                                     
console.log(data); // first log
debugger;
// inspect your object now

found["test"] = data;
delete data.id;
console.log(data); // second log
// inspect the object now, the property should be gone

O you could change what you are logging by drilling into the object:

data["id"] = 0;                                                     
console.log(data.id); // 0
found["test"] = data;
delete data.id;
console.log(data.id); // undefined
Alex Wayne
  • 178,991
  • 47
  • 309
  • 337