Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Implicit coercion for objects

Tags:

javascript

I am having troubles with implicit coercion with the + operator in JavaScript. Namely the priority order of valueOf and toString.

var obj = {};

obj.toString(); => "[object Object]"

obj.valueOf(); => Object {}

'Hello ' + obj; => "Hello [object Object]"

So obj is implicitly coerced to a string using the toString() method over valueOf();

var obj2 = {
    toString: function() {
        return "[object MyObject]"; 
    },
    valueOf: function() { 
        return 17;
    }
};

obj2.toString(); => "[object MyObject]"

obj2.valueOf(); => 17

'Hello ' + obj2; => "Hello 17"

So when I override the toString and valueOf methods, the + operator will coerce with valueOf.

What am I missing? Thanks.

like image 483
jamiltz Avatar asked Jun 30 '26 16:06

jamiltz


1 Answers

The answer can be found in a similar thread: valueOf() vs. toString() in Javascript

If the object can be transformed into a "primitive" JavaScript will try to treat it as a number. Otherwise string concatenation via the toString method is used. Without the valueOf method, JavaScript cannot tell how to convert the data, hence the object will be concatenated as a string.

If you're interested the precise specifications are available in the following pdf at around page 58: http://www.webreference.com/javascript/reference/ECMA-262/E262-3.pdf

Hope that helped :-)

like image 190
Jens Egholm Avatar answered Jul 02 '26 04:07

Jens Egholm



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!