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…
- If Type(x) is the same as Type(y), then
- If Type(x) is Undefined, return true: undefined == undefined
- If Type(x) is Null, return true: null == null
- If Type(x) is Number, then
- If x is NaN, return false: NaN != NaN
- If y is NaN, return false: NaN != NaN
- If x is the same Number value as y, return true: 2 == 2
- If x is +0 and y is −0, return true: 0 == 0
- If x is −0 and y is +0, return true: 0 == 0
- Return false: 2 != 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”
- 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
- 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
- If x is null and y is undefined, return true: null == undefined
- If x is undefined and y is null, return true: undefined == null
- If Type(x) is Number and Type(y) is String, return the result of the comparison x == ToNumber(y): 2 == “2”
- If Type(x) is String and Type(y) is Number, return the result of the comparison ToNumber(x) == y: “2” == 2
- If Type(x) is Boolean, return the result of the comparison ToNumber(x) == y: false == 0 and true == 1 but true != 2
- If Type(y) is Boolean, return the result of the comparison x == ToNumber(y)
- 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