What's the Difference?
The '==' Operator
Let's take an example here when comparing a string and an integer with the same value.
let a=1; let b='1'; console.log(a==b);
or wait let's try this
let a=1; let b=true; console.log(a==b);
WHAT?? How is it true??
You may be wondering how this is possible? well because the '==' operator takes only value into consideration, not the type. Therefore matches boolean true to 1 by converting one of them.
The '===' Operator
let a=1; let b='1'; let c=true; console.log(a===b); console.log(a===c);
This returns false for the values which are not of a similar type. This operator performs type casting for equality. If we compare 1 with '1' using ===, then it will return a false value.
When to use the '==' Operator
I don't usually recommend to use this often but you can use this when
- Checking if a value is null/undefined
- When you know both the operators of the same type
'==' Operator is Value based comparison
'===' Operator is Type+Value based comparison
So most of the times you should be using triple equals insead of double equals as it's more precise, accurate and doesn't bring up bugs which are not easy to find.