Updated on March 9, 2023
The latest guidance from Mozilla as of March 2023:
Information about an object is lazily retrieved. This means that the log message shows the content of an object at the time when it's first viewed, not when it was logged. For example:
const obj = {};
console.log(obj);
obj.prop = 123;
This will output {}
. However, if you expand the object's details, you will see prop: 123
.
If you are going to mutate your object and you want to prevent the logged information from being updated, you can deep-clone the object before logging it. A common way is to JSON.stringify()
and then JSON.parse()
it:
console.log(JSON.parse(JSON.stringify(obj)));
There are other alternatives that work in browsers, such as structuredClone()
, which are more effective at cloning different types of objects.
const mushrooms1 = {
amanita: ["muscaria", "virosa"],
};
const mushrooms2 = structuredClone(mushrooms1);
mushrooms2.amanita.push("pantherina");
mushrooms1.amanita.pop();
console.log(mushrooms2.amanita); // ["muscaria", "virosa", "pantherina"]
console.log(mushrooms1.amanita); // ["muscaria"]
Previous Guidance from MDN
The latest guidance from Mozilla as of February 2023:
Don't use console.log(obj)
, use console.log(JSON.parse(JSON.stringify(obj)))
.
This way you are sure you are seeing the value of obj
at the moment you log it. Otherwise, many browsers provide a live view that constantly updates as values change. This may not be what you want.