Comparisons…we all make them and it is one of the things that makes life interesting. Everyone has their likes/dislikes and their favorites and not so favorite. For example, we own horses. I have my favorite even though I work with and love each of them…but if I were comparing, my mare would win hands down. My wife would argue that…LOL.
So, in programming, we perform comparisons all the time. We compare two values and based upon that comparison, our program makes decisions. Today’s post is about the operators we use to make those comparisons. First up…equality…
[code lang=”js”]
// Create a comparison using ‘==’
var firstNum = 10;
var secondNum = 10;
if(firstNum == secondNum){
// Do something…
}
[/code]
In the above code, we are using the ‘==’ operator to decide if two variables (firstNum and secondNum) are equal. You may ask, “Why two equals signs?” One equals sign is used for assigning value. Do you notice the one equal sign in the var statements above? So we need two equals signs. Let’s look at another example…
[code lang=”js”]
// Create a comparison using ‘===’
var firstNum = 10;
var secondNum = 10;
if(firstNum === secondNum){
// Do something…
}
[/code]
This code is nearly a duplicate to the previous code, with one exception. We are using the ‘===’ operator. Notice the third equal (=) sign. So what is the difference? In the first example, we were asking the question, “Is firstNum equal to secondNum?” In the second example, we are asking, “Is firstNum EXACTLY equal to secondNum?” The two equals signs simply test value, while the three equals signs tests value and data type. In other words, we are asking, “Is firstNum’s value AND data type equal to secondNum’s?”
So what is the big deal? Well, we might have a scenario where the values equal, but the types do not. We could have the number/integer ten (10) and the string/text of ten (“10”). With two equals signs, comparing these returns true. With three, it would return false. The JavaScript engine does some type conversion with the two equals signs.
Now in, some cases, this may not make a difference, but could cause issues. Imagine you are doing addition. Remember how the plus (+) operator can also perform concatenation. If you try to add the number 10 with the string of 10, you would end up with 1010, not 20 in some situations.
So, bottom line…try to use three equals signs (===) as much as possible to avoid possible buggy issues down the road.
Happy Coding!
Clay Hess