Strict equality operators in JavaScript: === and !==

Posted on April 7th, 2009 in JavaScript by Jon Kruger

The first time you see this, you think it’s a typo. But yes, === and !== are valid operators in JavaScript.

These operators do a strict comparison of equality by comparing both the type and the value. It’s easier to explain if I show you an example.

// This line will return true because both things mean 2
'2' == 2
 
// This line will return false because on one side you have a string and
// on the other side you have a number.
'2' === 2

Here’s another example:

var x = null;
 
if (x == undefined) // true
{
    // do something
}
 
if (x === undefined) // false!
{
    // do something
}

The first if statement evaluates to true because JavaScript says that null means the same as undefined, but the second if statement evaluates to false because null is not exactly the same as undefined.

Why would you care about this? Well, for the simple JavaScript that we write to manipulate stuff on a page of HTML, it probably doesn’t matter. But if you’re writing a complicated JavaScript library, this may be something that you might use. If anything, it’s good to know what it means so that you don’t freak out when you see it in someone else’s code.


Kick It on DotNetKicks.com

One Response to 'Strict equality operators in JavaScript: === and !=='

Subscribe to comments with RSS or TrackBack to 'Strict equality operators in JavaScript: === and !=='.

  1. Damien said,

    on July 23rd, 2010 at 4:41 pm

    Thanks. Well explained :-)

Post a comment