Reputation: 35
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
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
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
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
Reputation: 996
because with + you are doing type coercion, and converting you object to string, try console.log("obj", "\n", obj);
Upvotes: 1
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