5

**** NOT A DUPE *** The duplicate referenced answer refers to JSON only ****

I am looking to avoid this when logging js vars to the console:

var user = {
  first: 'Jack',
  last: 'Green',
  age: 54
};
 
// plain console log
console.log(user);
 
// or with interpolation:
console.log(`User: ${user}`);

This ends up like:

{ prop1: 'value1', prop2: 2 }
 
User: [Object object]
DropHit
  • 1,695
  • 15
  • 28
  • 1
    Log the variable itself rather than a `.toString()` version of the variable as in `console.log('User: ', user);`. – Ouroborus Mar 08 '17 at 04:37

1 Answers1

6

Change the above example to:

var user = {
  first: 'Jack',
  last: 'Green',
  age: 54
};

// plain console log
console.log(JSON.stringify(user, undefined, 2));

// or with interpolation:
console.log(`User: ${JSON.stringify(user, undefined, 2)}`);

and now we get the nice looking output:

{
  "first": "Jack",
  "last": "Green",
  "age": 54
}

User: {
  "first": "Jack",
  "last": "Green",
  "age": 54
}
DropHit
  • 1,695
  • 15
  • 28