What’s the difference between == and === in JavaScript

Hey there! πŸ‘‹

If you’re reading this article this means you are either a beginner and I highly applaud you for being interested in this topic πŸ‘ or I guess you”re just looking around and found this valuable.

Disregarding your intentions, let’s get right down to it!

Two or three

The basic definition that applies to all programming languages regarding == and === is that they both do comparisons of data.

The only difference is that the latter one, i.e. === compares also the data type, whereas == does not.

Let’s head for an example in JavaScript:

const myFirstVariable = 0;
const mySecondVariable = "0";

console.log(myFirstVariable == mySecondVariable); // prints true

console.log(myFirstVariable === mySecondVariable); // prints false

Let me explain πŸ•΅οΈ

In the example above we have two variables; one is an integer and the other one is a string.

Now let’s ask a question: “Is the data assigned to the variables the same?”
Now let’s answer that: “Yes, it is. The both variables hold zero.”

And since both variables hold zero, that means that the data is the same, however the data types are different.

And let’s get back to the definition from above, that ==checks for data and === checks also for the data type.

That difference is so simple and there is nothing more, but from my experience, it is our fellow developers, who just do not use it properly and then is just misleads other (mostly beginner) developers.

Should I use == or ===?

My answer is, “well, it depends” πŸ™‚ .

If you’re coding your own project for example, a mvp of an application or you just don’t care about bugs coming up, you are very welcome to use ==, maybe because you don’t want to spend time dealing with types, which does take time.

But in every other single case I invite you to always use === sign and I recommend it from a very simple reason.

It is that if you are just not sure about the data type of the variable, if there is a string or an integer you better go and dig deeper into your code and find it out, because it will help you firstly, write better code, you will understand the code in more detail and lastly, you may even find a bug in the code, because one of your colleagues might have mistakenly forgot about setting up the type.

Hope you guys finally understood the difference between == and ===.

If there is still something unclear, just leave a comment below, I will get back to it.

Or if you’d like to explain some other programming practise also let me know in the comments below and very lastly, see you in the next article πŸ‘‹.

Yours in coding,