What gets logged in console.log() for objects and arrays?
Elad Tzemach
Posted on September 14, 2020
Have you ever used console.log(myObject)
and were confused by the result you got after expanding what was printed to the console?
For example:
const myObject = {
firstName: "Elad",
lastName: "Tzemach",
favoriteFood: "cake"
};
console.log(myObject);
// lots of other code
myObject.favoriteFood = "broccoli";
Will give give us this in the console:
Yay! 😍 I love cake! 🍰 🍰 🍰
Let's expand this:
What?? 😳 "broccoli"
?? What happened??
See that little blue icon "i" icon?
If you hover over it, you will see a tool tip saying "Value below was evaluated just now."
Evaluating with console.log()
Evaluating objects (or arrays) using console.log()
is done in an asynchronous manner: the reference to the object itself is passed to console
synchronously, and that is why we initially see the object with favoriteFood: "cake"
before we expand it - because that is what the object "looked like" at the time we logged it to the console.
However, if the object had been later modified and then we expanded it in the console, it would be evaluated to what it is equal to now (after the app code had finished running), so the data shown will have the updated values.
What can be done?
To avoid any confusion, one approach is to use:
console.log("users", JSON.stringify(users, null, 2));
Then we would just get the object at the time we called console.log()
, expanded by default: (although we won't be able to collapse it)
Another one is to simply deep clone the object and only then log it:
console.log({...myObject});
(Easily done by the spread operator if you don't have nested objects. If you do, you would have to use third-party libraries like Lodash
or ImmutableJS
)
Conclusion
Understanding how console.log()
works with objects and arrays could definitely save you some frustration!
And if you have made it till the end, i have a confession to make: i like broccoli too 😄
Happy coding!! 🚀
Posted on September 14, 2020
Join Our Newsletter. No Spam, Only the good stuff.
Sign up to receive the latest update from our blog.