6

**** 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]
1
  • 1
    Log the variable itself rather than a .toString() version of the variable as in console.log('User: ', user);. Commented Mar 8, 2017 at 4:37

1 Answer 1

7

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
}
Sign up to request clarification or add additional context in comments.

2 Comments

That's not pretty. There's no need for quotes around keys. Please, an answer that doesn't use JSON.
Huh looks good to me- thanks for the advice - you're a true genius and obviously bored.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.