Upgrade to Pro — share decks privately, control downloads, hide ads and more …

JavaScript Type Conversions

JavaScript Type Conversions

JavaScript Type Conversions and some explanations to the Gary Bernhardt's wat lighting talk

Orlando Del Aguila

March 13, 2015
Tweet

More Decks by Orlando Del Aguila

Other Decks in Programming

Transcript

  1. JavaScript
    Type
    Conversions

    View Slide

  2. JavaScript
    Primitives
    yes, js has primitives

    View Slide

  3. 1. undefined
    2. null
    3. number
    4. string
    5. boolean

    View Slide

  4. 1. undefined
    2. null yep, is not an object
    3. number
    4. string
    5. boolean

    View Slide

  5. JavaScript
    Binary
    Operators
    we are going to address only
    - and +

    View Slide

  6. On doubt
    check the spec

    View Slide

  7. http://www.ecma-international.org/ecma-262/5.1/#sec-11.6.1
    http://www.ecma-international.org/ecma-262/5.1/#sec-11.6.2

    View Slide

  8. + Operator

    View Slide

  9. If lprim or rprim are strings, then
    concatenate lprim and rprim and
    return the result

    View Slide

  10. - Operator

    View Slide

  11. ToNumber(lprim)
    -
    ToNumber(rprim)

    View Slide

  12. Examples

    View Slide

  13. var a, b;
    a = "bla";
    b = "ble";
    a + b; //=> "blable"
    a - b; //=> "NaN"
    a = "5";
    b = "4";
    a + b; //=> "54"
    a - b; //=> 1

    View Slide

  14. 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
    // error
    obj + 1;
    // valueOf
    // toString
    // error

    View Slide

  15. 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

    View Slide

  16. {} + [] //=> +[] == 0
    [] + {} //=> '' + '[object Object]' == '[object Object]'
    [] - {} //=> 0 - NaN == NaN
    {} - [] //=> -[] == -0

    View Slide

  17. View Slide

  18. WAT
    https://www.destroyallsoftware.com/talks/wat

    View Slide