Technical Article => Web => JavaScript

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.