Posts
114
Comments
130
Trackbacks
10
Quality Equality with JavaScript: "===" > "=="
Technorati Tags:

 

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

posted on Saturday, July 3, 2010 7:11 AM Print
Comments
Gravatar
# re: Quality Equality with JavaScript: "===" > "=="
RedriderX
10/4/2011 9:05 AM
Thanks this really cleared triple equal sign up for me.

Post Comment

Title *
Name *
Email
Comment *  
 
Tag Cloud