Sekrab Garage

Console.log pitfall

Console live logging mishaps and pitfalls and how to avoid them

TipJavaScript July 16, 21

According to MDN, there is one line in documenting console.log that sends a chill down your spine, and I could not find proper documentation for it.

Otherwise, many browsers provide a live view that constantly updates as values change.

So I wrote a simple test to see how that may happen.

var x = {name: "foo"};
console.log(x); = "bar";

x = {name: "oops"};

This will produce normal objects like this

Console.log output

But expand the objects:

Consolel log output

Notice how the first object name is no longer "foo", but rather "bar". The same happens when you are using console.dir and console.log({x}). The last log is because we reset the reference with a new object, which is not practical.

So to avoid that, you have two options. Either log out exact properties (, or as MDN suggests, clone the object before you log:

var x = {name: "foo"};
console.log(JSON.parse(JSON.stringify(x))); = "bar";

The output is

Console log output