A small trick on using console.log to print data in JavaScript

Summary

Debugging JavaScript often involves using console.log, but directly printing variables can lead to unclear output, especially when logging multiple items. While concatenating a label like console.log("user: " + user) might seem helpful, it disappointingly prints objects as [object Object], losing valuable detail. A more effective trick is to wrap the variable in an object literal, using console.log({user}). This method leverages JavaScript's shorthand property names to output a clear, self-identifying object like { user: { name: 'test' } }, significantly enhancing readability and making it easier to trace data flow for objects, undefined, and null values.

When debugging JavaScript application, one may frequently use console.log to print data so that it is easy to debug when issue occurs and also helps on understand the data flow. The common way of printing a variable would be something like. 

let user = {
    name: "test"
};

console.log(user);

In this case it will print:

{ name: 'test' }

This is OK when there is no much logging or the program is not complicated. But it becomes difficult to debug if there are lots of variables to be printed as there is no clear indication on which variable or object it is.

So in this case one may add some extra logging when writing the console.log statement.

let user = {
    name: "test"
};

console.log("user: " + user);

However after running the code, it would be disappointing as it doesn't print what is expected, the user variable is printed as just some type information but not the actual properties and their values.

user: [object Object]

Is there a better way for logging the object without writing complicated code by looping through the object and logging each property individually? Yes, there is, actually if we put the variable inside {} and print it, we would see something useful.

let user = {
    name: "test"
};

console.log({user});

The output will be like:

{ user: { name: 'test' } }

How this works is that it actually creates a new object and tries to print this object where the property name is the variable name and the value is the variable itself. This is much more readable now. And it can print undefined or null variable in a readable manner.

let user = undefined;
console.log({user});

let user = null;
console.log({user});

Output is:

{ user: undefined }
{ user: null }

Hope this is useful when you try to debug something in JavaScript.

JAVASCRIPT CONSOLE.LOG DEBUGGING

  RELATED

  COMMENTS

4
Anonymous
Sep 3, 2019 at 11:02 am

Why not just `console.log('user', user)`?

Ke Pi
Sep 3, 2019 at 11:14 am

this works but it seems more work?

Anonymous
Sep 6, 2019 at 10:25 am

Or:

console.dir(user);
Anonymous
Sep 6, 2019 at 10:43 am

it doesn't print user as the label, it only prints the object itself.