Type Coercion Rules In Javascript

In order for readers to be able to understand those crazy equality examples in Javascript Catches And Pitfalls – part1 (equality and comparisons), here’s a list of rules Javascript follows when coercing variable types. I would’ve put this into the mentioned post, but I’m afraid the post would get waaaaaaaaay to long.

So here we go…

    1. If Type(x) is the same as Type(y), then
        1. If Type(x) is Undefined, return true: undefined == undefined
        1. If Type(x) is Null, return true: null == null
        1. If Type(x) is Number, then
            1. If x is NaN, return false: NaN != NaN
            1. If y is NaN, return false: NaN != NaN
            1. If x is the same Number value as y, return true: 2 == 2
            1. If x is +0 and y is −0, return true: 0 == 0
            1. If x is −0 and y is +0, return true: 0 == 0
            1. Return false: 2 != 1
        1. If Type(x) is String, then return true if x and y are exactly the same sequence of characters (same length and same characters in corresponding positions). Otherwise, return false: “a” == “a” but “a” != “b” and “a” != “aa”
        1. If Type(x) is Boolean, return true if x and y are both true or both false. Otherwise, return false: true == true and false == false but true != false and false != true
        1. Return true if x and y refer to the same object. Otherwise, return false: var o = {}; o == o but o != {} and {} != {} and [] != [] … etc etc, all objects are eqeq only if it’s the same 
    2. If x is null and y is undefined, return true: null == undefined 
    3. If x is undefined and y is null, return true: undefined == null 
    4. If Type(x) is Number and Type(y) is String, return the result of the comparison x == ToNumber(y): 2 == “2” 
    5. If Type(x) is String and Type(y) is Number, return the result of the comparison ToNumber(x) == y: “2” == 2 
    6. If Type(x) is Boolean, return the result of the comparison ToNumber(x) == y: false == 0 and true == 1 but true != 2 
    7. If Type(y) is Boolean, return the result of the comparison x == ToNumber(y)
    8. If Type(x) is either String or Number and Type(y) is Object, return the result of the comparison x == ToPrimitive(y): ToPrimitive means implicit valueOf call or toString if toString is defined and valueOf is not

Leave a Reply

Your email address will not be published. Required fields are marked *