Technorati Tags:
JavaScript
Did you know that there are two equality operators in JavaScript?
The one that's used most often is the double equal sign ("==") operator. The "==" operator does type coercion. The following example returns true, even though we're comparing a string and a number:
if ('5' == 5)
That's not too bad, but you probably wouldn't expect the following examples to return true:
if (0 == '')
if (0 == false)
if (false == undefined)
if ("\r\n" == 0)
They all do though, thanks to JavaScript's concept of "truthiness".
The lesser-known JavaScript equality operator is the triple equal sign strict equality operator ("==="). It checks that values are the same value and the same type, so these all return false:
if ('5' === 5)
if (0 === '')
if (0 === false)
if (false === undefined)
if ("\r\n" === 0)
(The corresponding strict inequality operator is "!==").
Douglas Crockford, author of "JavaScript: The Good Parts", recommends always using the strict equality operators, and I recommend always following the WWDD (What Would Doug Do?) principle when it comes to JavaScript.
You can watch a great Douglas Crockford presentation about the good, the bad, and the ugly of JavaScript here: http://www.videosurf.com/video/javascript-the-good-parts-61213764?vlt=ffext