ranjan
ranjan

Reputation: 35

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

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

Upvotes: 2

Views: 69

Answers (4)

fedesc
fedesc

Reputation: 2610

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))

Upvotes: 3

Lewis
Lewis

Reputation: 14866

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.

Upvotes: 1

Anna Vlasenko
Anna Vlasenko

Reputation: 996

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

Upvotes: 1

Krzysztof Krzeszewski
Krzysztof Krzeszewski

Reputation: 6714

String of object is "[object Object]".

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

console.log(String({}))

Upvotes: 1

Related Questions