:::: MENU ::::

Tuesday, July 24, 2012

I’ve been doing more JavaScript lately than I have in the past and am starting to take a closer look at semantics. In particular, the strange looking exactly equal operator with the three equal signs, ===. Someone who’s been working a career of C, C++, Java, and C# might not be familiar with exactly equalbecause equality in these languages is already strongly typed.

The point is that JavaScript is not strongly typed, so the development experience is different. The subject of this post addresses the typing issue associated with equality and the meaning of the JavaScript exactly equal operator.

The primary difference between the equal, ==, and exactly equal, ===, operator is typing. They both test for equality, but exactly equal tests for type too.  Here’s an example:

var fiveInt = 5;
var fiveString = "5";

var equal = fiveInt == fiveString;
var exactlyEqual = fiveInt === fiveString;


In the code above, fiveInt is a integer type and fiveString is a string type.  The equal operator expression sets the equal variable to true.  However, the exactly equal operator expression sets the exactlyEqual variable tofalse.  The exactly equal operator expression in the example above results in false because it’s comparing two variables that are different types.

Most of the time, it seems like exactly equals is what you should do because it’s safer and avoids errors through false positives. However, I can see where equals would be useful for when reading screen input that is read as a string and being able to make a quick comparison without the extra conversion/validation code that would be required in C#.

More