If you have worked with programming languages, you know that all programming languages have a comparison operator, i.e. ==, which is used to compare two values. But JS took this one step further. JS also has a === operator, which is known as Strict Equality Comparison.
If you search the difference between == and === in JS on the internet, all the articles will claim:
〝== check the values whereas === check both values and the types of both value.
〞
And you are totally WRONG!
Before creating our own conclusion, let’s first see what the official documentation of JavaScript has to say! If you check the official ECMAScript documentation under point 7.2.14 it says,
The first line itself says that == check the types of “x” and “y”; if both the types are the same then it will call === internally! Now let’s see the documentation of === below.
Here you can see === will also check if both the types are equal or not. If the types of “x” and “y” are not the same, it will straightaway give false without even checking the values.
So what’s exactly happening here? Let’s simply this!
If you use == (e.g.: x == y), it will first check the types of x and y then:
If you use === (e.g.: x === y), it will first check the types of x and y, then:
〝== and === both checks the types, it just that == performs coercion (type conversion) whereas === doesn’t.
〞
If you look closely, it actually makes sense why JavaScript maker did this. When you use == on two different types of operands, for e.g., “14” == 14, which returns true, JS needs to convert the “14” to 14 and to do so JS need to first check the types of both the operands. Without checking types, JS cannot just convert the types randomly.
If you've enjoyed reading this blog and have learnt at least one new thing, do subscribe to recieve updates whenever I post a new article directly to your inbox and do share on Twitter with your friends.