Geeks With Blogs
Brian Schroer Don't Call Me Mort!
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:

Posted on Saturday, July 3, 2010 7:11 AM JavaScript | Back to top

Comments on this post: Quality Equality with JavaScript: "===" > "=="

# re: Quality Equality with JavaScript: "===" > "=="
Requesting Gravatar...
Thanks this really cleared triple equal sign up for me.
Left by RedriderX on Oct 04, 2011 9:05 AM

Your comment:
 (will show your gravatar)

Copyright © Brian Schroer | Powered by: