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")]
-
Who wants to close this post????Maizere Pathak.Nepal– Maizere Pathak.Nepal2013年04月21日 17:50:02 +00:00Commented Apr 21, 2013 at 17:50
3 Answers 3
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"
6 Comments
.valueOf() object returns a plain object which is not a string. It's just the same object. The + operator returns a string for reasons that I explained in my answer below the first code example..valueOf() is not the same as the .toString(), and does not return a string.o === o.valueOf(); may not always be true. Implementation specific according to ECMA-262.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.
7 Comments
+ is a string in this case. If it were a number, you would be adding it.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.