In JavaScript not all comparisons are created equal… see what I did there. Let’s say we’re comparing two values like this:

if ( 42 == “42” ) {
 return “The meaning of life is 42”; 
}

The use of “==“ will compare two values regardless of their type, so in this example, it will return “The meaning of life is 42”. Used correctly this can be fine of course, but it can leave you open to issues like this:

var meaingOfLife = “41”;

if (meaningOfLife == 41) {
  meaningOfLife += 1;
}
return meaingOfLife; 

In this example, we’ve done the same comparison but then tried to add to the meaningOfLife variable which we can’t do because it’s a string, not a number. This is why as a general rule it’s best practice to use “===” for comparison as it will compare both value and type. Here’s an updated example:

var meaingOfLife = “41”;

if (meaningOfLife === 41) {
  meaningOfLife += 1;
}
return meaingOfLife; 

This version will correctly return “41” due to the fact the if statement will return false because the items match in value but not type. Do yourself a favour and default to “===“, it’s the comparison you’re likely to want the majority of the time.

%d bloggers like this: