When == isn't equal

25 October 2008 · 2 minute read · ajax · javascript

Earlier this month I did a post about common mistakes made by developers new to JavaScript but there's a point I forgot to cover which I see a lot of.

Nearly every language has a different way in which it handles equality. SQL has a single equal sign ala:

SELECT [COLUMN1]
FROM [Table]
WHERE [COLUMN2] = 'some value'

Or you have compiled languages like C# which use ==:

if(someValue == someOtherValue){
}

Or for some wierd reason LINQ uses the keyword equal when it does join operations...

And then we get to JavaScript. JavaScript actually has 2 equality comparison, == and === (the same exists for inequality in != and !==), but why?
You need to remember that JavaScript is an loosly typed language, you don't define a variable type, you define it by the the assignment. This also means you can retype a variable during its life.

So what's the got to do with the equality operators? Well the choice of equality comparison depends how strongly checked you want to make your comparison.
Say what?

Well, == compares the values at a primitive level, regardless of their types, where as === also does a type comparison. Take the following example:

var someValue = 1;
alert(someValue == '1');
alert(someValue === '1');

Both alerts will show true, but in the first alert we're comparing a number to a string. That's likely to be a problem if you're comparing two variables! It's a good way to get unexpected behavior from your JavaScript.
As Ruben has correctly pointed out below the first alert shows true and the second shows false (note - don't blog while watching TV, you tend to not pay attention :P). Because we are comparing a number to a string we generally do not want it to be true. This is most commonly noticed when comparing two variables and can lead to unexpected behavior during script execution.

So should you ever use an untyped equality comparison? Well yes if the type of whats being compared is either a) definitely known (ie - prechecked) b) not going to have bearing on the continued operation of the script.

Well there's something to keep in mind the next time you think JavaScript is out to get you with unexpected operation.


Published: 2017-10-30 16:57:41 +1100 +1100, Version: 9ff0cbb