Reputation: 2413
What will be the output of the of following code:
console.log({}.valueOf()+15);//Output:[object Object]15
Will the return value from the .valueOf() method be string in the above code or is simply an object since .toString() will result in same but with this method returned value will be string anyhow.I just wanted to know what will be the type of the value the .valueOf() returns in above code.If return value is a string ,for what other object will valueOf() method returns string value except for [new String("abc")]
Upvotes: 2
Views: 161
Reputation: 56
The .valueOf()
of a plain object will be the same object. (This is NOT the same as its .toString()
method.)
var o = {};
typeof o.valueOf(); // "object"
o === o.valueOf(); // true
The +
operator sees that you're not using a number for the first operand, so instead of addition, it does string concatenation and calls the .toString()
value of both of its operands.
That's why you get [object Object]15
.
You can test this by changing the toString()
output.
var o = {};
o.toString = function() { return "foobar" }
o.toString(); // "foobar"
o + 15; // "foobar15"
o.valueOf() + 15; // "foobar15"
Upvotes: 3
Reputation: 10590
To get the type of an object in JS, you can use the typeof function:
typeof({}) // outputs 'object'
typeof({}.valueOf()) // outputs 'object'
typeof({}.valueOf()+15) // outputs 'string'
This indicates that the value coercion is taking place when trying to "add" 15, which instead is interpreted as string concatenation.
Upvotes: 0
Reputation: 324630
valueOf
returns a primitive value. Exactly what type of primitive value depends on the object.
To demonstrate:
typeof Number(0).valueOf(); // number
typeof Boolean(0).valueOf(); // boolean
The point is that, whatever it returns, it is a primitive value. toString
, on the other hand, always returns a string.
In the case of {}
, there is no valueOf
method other than the root Object.prototype.valueOf
, which is identical to Object.prototype.toString
, returning a string of the form [object Constructor]
. Which being a string results in concatenation with 15
.
Upvotes: 3