JavaScript Type Conversions and some explanations to the Gary Bernhardt's wat lighting talk
JavaScriptTypeConversions
View Slide
JavaScriptPrimitivesyes, js has primitives
1. undefined2. null3. number4. string5. boolean
1. undefined2. null yep, is not an object3. number4. string5. boolean
JavaScriptBinaryOperatorswe are going to address only- and +
On doubtcheck the spec
http://www.ecma-international.org/ecma-262/5.1/#sec-11.6.1http://www.ecma-international.org/ecma-262/5.1/#sec-11.6.2
+ Operator
If lprim or rprim are strings, thenconcatenate lprim and rprim andreturn the result
- Operator
ToNumber(lprim)-ToNumber(rprim)
Examples
var a, b;a = "bla";b = "ble";a + b; //=> "blable"a - b; //=> "NaN"a = "5";b = "4";a + b; //=> "54"a - b; //=> 1
var obj = {valueOf: function valueOf() {console.log("valueOf");return {}; // not a primitive},toString: function toString() {console.log("toString");return {}; // not a primitive}};obj - 1;// valueOf// toString// errorobj + 1;// valueOf// toString// error
var func = function () {console.log('exec');return {valueOf: function valueOf() {console.log("valueOf");return {}; // not a primitive},toString: function toString() {console.log("toString");return {}; // not a primitive}};};func() + 1;// exec// valueOf// toString// error
{} + [] //=> +[] == 0[] + {} //=> '' + '[object Object]' == '[object Object]'[] - {} //=> 0 - NaN == NaN{} - [] //=> -[] == -0
WAThttps://www.destroyallsoftware.com/talks/wat