How to Display a JavaScript Object in the Console

In this tutorial, we are going to learn about how to log or display a JavaScript object in the console.


Consider we have below JavaScript object:
 var user = {
    id: 1,
    firstName: 'Ramesh',
    lastName: 'Fadatare',
    emailId: 'ramesh@gmail.com',
    age: 29,
    address: {
        street: 'kondhwa',
        pincode: '12345'
    }
  }
Now, if we try to log an object with the text we can see an error.
console.log('This is object'+ user); // wrong way
Output:
This is object[object Object]

You can solve the above problem by passing the user object as a second argument to the console.log() method like:
console.log('This is object', user); // correct way
You can also use JSON.stringify() method like:
console.log('This is object -> ' + JSON.stringify(user)); // this also works

Complete Example

Here is the complete example with output:
function test() {
  var user = {
    id: 1,
    firstName: 'Ramesh',
    lastName: 'Fadatare',
    emailId: 'ramesh@gmail.com',
    age: 29,
    address: {
        street: 'kondhwa',
        pincode: '12345'
    }
  }

  console.log('This is object'+ user); // wrong way

  console.log('This is object', user); // correct way

  console.log('This is object -> ' + JSON.stringify(user)); // this also works

}
test();
Output:
This is object[object Object]
This is object {id: 1, firstName: "Ramesh", lastName: "Fadatare", emailId: "ramesh@gmail.com", age: 29, …}
This is object -> {"id":1,"firstName":"Ramesh","lastName":"Fadatare","emailId":"ramesh@gmail.com","age":29,"address":{"street":"kondhwa","pincode":"12345"}}

Free Spring Boot Tutorial | Full In-depth Course | Learn Spring Boot in 10 Hours


Watch this course on YouTube at Spring Boot Tutorial | Fee 10 Hours Full Course

Comments