JavaScript: Loose (== and !=) and Strict (=== and !==) Equality Operators
Loose equality does not include type-checking, Strict equality does!
Let's understand this with an example.
Example
let score1 = 100;
let score2 = "100";
console.log(score1 == score2); // true
console.log(score1 === score2); // false
We have two variables, one contains value 100 as a number and the other contains the same, but as a string.
So, in loose equality, it typecasts automatically, converting the string into the number. Finally, resulting in true
.
On the other hand, in strict equality, it does not typecast, but it checks types, which are not the same, resulting in false
.
But, there is a twist!
Be careful with the strings. Well, they look the same, but sometimes they are objects, not strings.
Consider the following example.
let name1 = "Dan";
let name2 = new String("Dan");
console.log(name1 == name2); // true
console.log(name1 === name2); // false
// the twist
console.log(typeof(name1)); // 'string'
console.log(typeof(name2)); // 'object'
Here, both name1 and name2 look like strings, but ...
Check out the previous article, to understand the difference.
Fair enough!
Thanks for reading.