Javascript "==" vs "==="
Javascript difference between double and triple equals.
Working with javascript you might have encountered, the double and triple equals, operators. People, do get confused on when to use any of these are the any specific cases or what ? In this article let's uncover more about it.
Equality Operator ==
The
==
operator is the equality operator in JavaScript.It performs type coercion if the operands are of different types, meaning it tries to convert the operands to the same type before making the comparison.
For example, if you compare a string and a number using
==
, JavaScript will attempt to convert the string to a number before making the comparison.
Example:
console.log(5 == '5') // true
Strict Equality Operator ===
The
===
operator is the strict equality operator.It does not perform type coercion. It checks both the value and the type of the operands. If they are of different types, the comparison evaluates to false.
This is considered safer and is generally recommended unless you explicitly want type coercion.
Example:
console.log(5 === '5') // false
console.log(5 === 5) // true
Common Pitfalls
Due to the potential for unexpected results with type coercion, most of the developers prefer using ===
to avoid subtle bugs. When in doubt, using ===
is generally a safer choice.
Below are some examples, showing the difference between ===
and ==
0 == false // true, because of type coercion
0 === false // false, because the types are different
The value of 0
when checked with false
is same, because 0
and false
both have same value in JavaScript, but when checked against type and value, the value is false because 0
is a number
and false
is boolean
. So, here values are same, types are different, that's why we can see the effect of type coercion in this.
console.log("" == false) //true
console.log("" === false) //false
In first case ==
returns true
, because in javascript empty string and false is considered equal. Whereas, in second case types are different and hence ===
returns false
.
The image below is a truth table explaining type equality in javascript:
Image source: https://dorey.github.io/JavaScript-Equality-Table/
Which, one to use then ?
Now, since we have got a better understanding of the difference between, ==
and ===
, now the question is, when to use these ?
In my opinion, I personally have never used ==
cause, I find it useless to be true. Why would, I compare only the values and not their type, when I am making a equality comparison. Its a very rare case or to be true none, which will require you to use ==
, even though using it will get your work done, but not checking the type can induce potential bugs. So, the safer option is always go with ===
.
If you like my work, subscribe to my newsletter to never miss an update. Also, do support me by liking, commenting and sharing the article. These small things, keep me motivated to contribute such content ๐.