How can I make console.log show the current state of an object?

Wesley picture Wesley · Sep 12, 2011 · Viewed 97.8k times · Source

In Safari with no add-ons (and actually most other browsers), console.log will show the object at the last state of execution, not at the state when console.log was called.

I have to clone the object just to output it via console.log to get the state of the object at that line.

Example:

var test = {a: true}
console.log(test); // {a: false}
test.a = false; 
console.log(test); // {a: false}

Answer

evan picture evan · Sep 12, 2011

I think you're looking for console.dir().

console.log() doesn't do what you want because it prints a reference to the object, and by the time you pop it open, it's changed. console.dir prints a directory of the properties in the object at the time you call it.

The JSON idea below is a good one; you could even go on to parse the JSON string and get a browsable object like what .dir() would give you:

console.log(JSON.parse(JSON.stringify(obj)));