What's the main difference between == and ===? The == is a special boolean operator that tells the compiler to do some type coercion under the hood and then, after the type coercion, check to see if its still the same value. But often, and by often I mean almost always, this behavior is not predictable and gives mixed results. Examples:
'' == '0' // false
0 == '' // true
0 == '0' // true
false == 'false' // false
false == '0' // true
false == undefined // false
false == null // false
null == undefined // true
' \t\r\n ' == 0 // true
Make sense? The answer is no, not really. This makes little sense unless you've spent the time to study case-by-case how the compiler will type coerce and evaluate these values. I highly recommend not wasting your time and, instead, simply using the ===.The === does no type coercion. It simply evaluates the types of the values and then the values themselves. It will always tell you whether any two values are exactly the same.
Regardless, always use === or your going to have a bad time.
Is this concept misconstrued? Often!
== is the same as === when the values you're evaluating are of the same type, but are NOT the same when they are of different types. (They are also the same for reference checks, but this is not always the case). Also, the performance of === is faster than == because no type coercion is done if the two values are not of the same type.
References
http://www.c-point.com/javascript_tutorial/jsgrpComparison.htm
http://www.ecma-international.org/ecma-262/5.1/#sec-11.9.3
No comments:
Post a Comment