DEV Community

Elad Tzemach
Elad Tzemach

Posted on

What gets logged in console.log() for objects and arrays?

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";
Enter fullscreen mode Exit fullscreen mode

Will give give us this in the console:

Screen Shot 2020-09-13 at 7.36.39 PM

Yay! 😍 I love cake! 🍰 🍰 🍰

Let's expand this:

Screen Shot 2020-09-13 at 7.39.30 PM

What?? 😳 "broccoli"?? What happened??

See that little blue icon "i" icon?

Screen Shot 2020-09-13 at 7.42.39 PM

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));
Enter fullscreen mode Exit fullscreen mode

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)

Screen Shot 2020-09-13 at 8.05.23 PM

Another one is to simply deep clone the object and only then log it:

console.log({...myObject});
Enter fullscreen mode Exit fullscreen mode

(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!! πŸš€

Top comments (0)