Javascript
JavaScript Fundamentals -- Logical and Comparison Operators

Comparison Operators -- Equality and Inequality

PRO

Two of the most used comparison operators in JavaScript are the equality and inequality operators. We frequently need to check if one variable is equal to another or if it's not equal to some value. You can compare two variables for equality using the == operator or the === operator. You can compare for inequality with the != and !== operators.

So why are there two operators for each comparison? That's because JavaScript has two types of comparison: abstract and strict. The == and != operators use abstract comparison. What this means is that if you are comparing two variables of different types, it converts one of them to be the same type as the other one and then does the comparison. Take the following example:

console.log(1 == '1');

We know from our JavaScript variables videos that there are two types here: number and string. It's also obvious by looking at this comparison that these two values are not equal to each other. But with an abstract comparison, the output here is true. That's because JavaScript converts the two values to the same type (either converting both to a string or both to a number) and then does the comparison. After they're both the same type, then we would expect the output to be true. The same happens with the != operator.

With strict comparison in JavaScript, though, that conversion is not done. The comparison is made exactly as you provide it. So let's change our example slightly:

console.log(1 === '1');

We are now doing a strict comparison. JavaScript is not going to convert the variables to be the same type, so the number 1 and the string '1' are compared exactly as provided and we get false as the output.

Follow along by forking this StackBlitz.

If you'd like to read more about comparison operators, check out this blog post.