javascriptecmascript-6template-literals

Javascript ES6 console.log object using template literal


I have simple object that I want to display in console

var obj = { name: 'John', age: 22 }

If I type:

console.log(obj)

Object { name: "John", age: 22 }

If I type:

console.log('my object is: ' + obj)

my object is: [object Object]

console.log('my object is: %o', obj)

my object is: Object { name: "John", age: 22 }

How can I achieve this using a template literal?

If I type:

console.log(`my object is: ${obj}`)

my object is: [object Object]


Solution

  • You could serialize the object with JSON.stringify.

    var obj = { name: 'John', age: 22 };
    console.log(`my object is: ${JSON.stringify(obj)}`);