The \'Wat\' talk for CodeMash 2012 basically points out a few bizarre quirks with Ruby and JavaScript.
I have made a JSFiddle of the results at http://jsfid
I second @Ventero’s solution. If you want to, you can go into more detail as to how +
converts its operands.
First step (§9.1): convert both operands to primitives (primitive values are undefined
, null
, booleans, numbers, strings; all other values are objects, including arrays and functions). If an operand is already primitive, you are done. If not, it is an object obj
and the following steps are performed:
obj.valueOf()
. If it returns a primitive, you are done. Direct instances of Object
and arrays return themselves, so you are not done yet.obj.toString()
. If it returns a primitive, you are done. {}
and []
both return a string, so you are done.TypeError
.For dates, step 1 and 2 are swapped. You can observe the conversion behavior as follows:
var obj = {
valueOf: function () {
console.log("valueOf");
return {}; // not a primitive
},
toString: function () {
console.log("toString");
return {}; // not a primitive
}
}
Interaction (Number()
first converts to primitive then to number):
> Number(obj)
valueOf
toString
TypeError: Cannot convert object to primitive value
Second step (§11.6.1): If one of the operands is a string, the other operand is also converted to string and the result is produced by concatenating two strings. Otherwise, both operands are converted to numbers and the result is produced by adding them.
More detailed explanation of the conversion process: “What is {} + {} in JavaScript?”