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 full-size slide

  2. JavaScript
    Primitives
    yes, js has primitives

    View full-size slide

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

    View full-size slide

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

    View full-size slide

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

    View full-size slide

  6. On doubt
    check the spec

    View full-size 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 full-size slide

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

    View full-size slide

  9. ToNumber(lprim)
    -
    ToNumber(rprim)

    View full-size slide

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

    View full-size slide

  11. 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 full-size slide

  12. 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 full-size slide

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

    View full-size slide

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

    View full-size slide