What is the difference between ‘==’ and ‘===’? And why you need to know.

3 min read

Have you ever been comparing two values in some kind of conditional statement in your Javascript (I think we all do all the time), and you weren’t getting what you expected?

We need to compare two values all the time, and well, we have a handful of ways to do so but here we are going to look at these two operators, ‘==‘ and ‘===‘. These two operators might look to be doing the same thing on the surface, returning a boolean value if the two values are equal or not. However, there is a big difference and it’s essential to understand the differences.

You can also consider ‘!=‘ and ‘!==‘ for everything we discuss here.

Loose Equality

First, let’s look at ‘==‘. You will hear this referred to as ‘loose equality’ operator.

Loose Equality Example

Wait, what? Why are all these true?

The most important thing to remember is something Javascript does called type coercion. When using this operator Javascript will take those operands and only make the comparison after attempting to convert them to a common type.

Type coercion can be problematic for us Javascript developers. After all, that’s why so many are using Typescript to have a strong types during development.

If we are waiting for some value to determine a conditional case or conditional render we could very well get true or false when we are not expecting to, possibly breaking things or rending the wrong thing (or nothing).

Strict Equality

Now comes the ‘===‘ operator. This will now evaluate the two operands without type coercion.

Operands of different types are considered to be different. It will only return true if both the value and the type match for both operands. This is important because we do not have to worry about Javascript’s type coercion giving us a false positive(or negative), thus making your code just a little more type-safe and explicit.

Let’s take a look at these console.logs comparing the same values as before, but now with strict equality checks.

Strict Equality Example

As we can see these evaluations are much more explicit and leave less wiggle room with Javascript’s type coercion. If we stay aware of this we can avoid errors in our code that can be associated with ‘==’ and how Javascript treats the two operands in this situation.

Here is a great resource you can bookmark for reference. https://dorey.github.io/JavaScript-Equality-Table/#two-equals

I would love to hear your thoughts on the topic.