Friday, July 22, 2011

When do I use the === operator in JavaScript?

As new JavaScript programmers spend time with the language they often run into an operator they are unfamiliar with.  Most of us are familiar with the double equals (==) operator.  But what does the triple equals (===) operator, aka strict equals operator, do?  Why would we use it over ==?

Let me begin by explaining how the == operator works and then contrast the === operator.  Suppose I have the following code:
     var aNum = 3;
     var aStr = “3”;
     console.log(aNum == aStr);
     // output is true

Even though aNum is a number and aStr is a string… the variables are considered equal by the == operator.  This is because == will attempt to convert the variables to the same type before comparing them.  As long as you are aware that happens, it is usually OK, and sometimes helpful. 

Now let’s look at the same code with the === operator:
     var aNum = 3;
     var aStr = “3”;
     console.log(aNum === aStr);
     // output is false

The === operator makes no attempt to convert the variables before comparing, so of course the variables are not equal. 

To summarize, any time you are doing an equality comparison when variable type does matter, use the === operator.  If you don’t care what the variable’s type is, or specifically want type coercion, use the == operator.  

No comments:

Post a Comment