In JS, console.log behaves in different ways as shown in code. Why?

Viewed 49

In the code below, console.log(obj) and console.log("obj"+"\n"+obj) behaves in two different way in output.

const obj = new Object()
obj.firstName = 'Jack'
obj.lastName = 'Reacher'
obj.isTrue = true
obj.greet = function(){
  console.log('hi')
}

console.log(obj)//getting all the members


console.log("obj"+"\n"+obj)// not getting any member

4 Answers

Because by doing this:

("obj"+"\n"+obj)

You are turning the object to a string without stringifying it.

try

const obj = new Object()
obj.firstName = 'Jack'
obj.lastName = 'Reacher'
obj.isTrue = true
obj.greet = function(){
  console.log('hi')
}

console.log(obj)//getting all the members


console.log("obj"+"\n"+JSON.stringify(obj))// not getting any member

Update - Having a closer look

You also have a function which will not be stringified with JSON.stringify() unless you deal with it first as such:

const obj = new Object()
obj.firstName = 'Jack'
obj.lastName = 'Reacher'
obj.isTrue = true
obj.greet = function() {
  console.log('hi')
}

console.log(obj)

// DEALING WITH FUNCTION
obj.greet = obj.greet.toString();


console.log("obj" + "\n" + JSON.stringify(obj))

Because in the second console, using string + obj will result in the object to be converted to string via this method Object.prototype.toString. You can check this article for more details about Type Conversion in JavaScript.

To solve your issue then you can either use JSON.stringify to convert the object into JSON string then print it. But JSON.stringify will intentionally convert some data or objects into string.

Nodejs supports a method for inspecting JavaScript objects util.inspect. It will print the object thoroughly. You better use this method instead.

String of object is "[object Object]".

When you add an object to the string it automatically is converted into the string

console.log(String({}))

because with + you are doing type coercion, and converting you object to string, try console.log("obj", "\n", obj);

Related