DCSIMG
JavaScript comparison operators : == and === - Pini Dayan

Pini Dayan

The best thing about a boolean is even if you are wrong, you are only off by a bit.

JavaScript comparison operators : == and ===

When we try to read a language guide book we usually or always skip the operators guide right? I mean , come on , don't we all know how to write JavaScript? What can be simpler then to use the == and != operator in JavaScript like this:

if (str == 'SomeString')
{
   //Do something
}

But as it turns out there are 2 more operators in JavaScript which most developers i know never heard about,The !== and the ===operators. Trying to figure out what is the difference between == and === on the netleads to the following observation:

The == is an operator to check equality, The === is an operator to check identity. Ok but what does it mean exactly. As it turns out the == and the != do type conversion under the hood when they test for equality. (While === and !=== does not!!!)

Here is a simple example of what i am trying to explain

<script>     
   
       alert(5 == "5");   //Prints true
       alert(5 === "5");  //Prints false
   
</script>

This is because the first alert do a type conversion first , which means the String is  converted first to a Number and only then being compared.
The striker === operator does not do any type conversion so the result is false.

Here are a couple more samples

1. null and undefined are both "falsy" values right? so

alert(null == undefined); will result a true because they both converted to boolean first while
alert(null === undefined); will result false.

2. true is converted to 1 and false is converted to 0, so

alert(1== true); will result a true.
alert(1=== true); will result false.

So as you can see === is more striker. It check both value and type.

Hope this helps.

Pini

Comments

Shlomo said:

שימושי, תודה רבה

# December 18, 2008 12:05 PM

Pini Dayan said:

בכיף :-)

# December 18, 2008 3:06 PM

עדי said:

מאוד שימושי לא הכרתי את התנאי הזה.

# December 18, 2008 5:39 PM
Leave a Comment

(required) 

(required) 

(optional)

(required) 


Enter the numbers above: