Today's Question:  What does your personal desk look like?        GIVE A SHOUT

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

  sonic0002        2019-09-03 10:24:24       13,526        4    

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.

DEBUGGING  CONSOLE.LOG  JAVASCRIPT 

Share on Facebook  Share on Twitter  Share on Weibo  Share on Reddit 

  RELATED


  4 COMMENTS


Anonymous [Reply]@ 2019-09-03 11:02:35

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

Ke Pi [Reply]@ 2019-09-03 11:14:29

this works but it seems more work?

Anonymous [Reply]@ 2019-09-06 10:25:13

Or:

console.dir(user);
Anonymous [Reply]@ 2019-09-06 10:43:12

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