Inequality In Equality
The story of inequalities between Equality operator (==) and Strict Equality operator (===) in Javascript
JavaScript is a weakly typed programming language. What does weakly typed mean, you ask? Well ๐ค Weakly typed means that while declaring a variable you don't need to provide its type
. JavaScript will figure out that variable's type
on the fly.
But this protocol of type-checking creates a glaring problem. For example, how will a programmer distinguish between the string "3" and the number 3? To resolve this issue, JavaScript has two equality-checking operators, one is the simple Equality operator (==) and the other is the Strict Equality operator (===)
Let us discuss them in detail ๐
Equality operator ๐๐ป ==
The equality operator compares value of operands after attempting type conversion on both the operands to a common type. In layman terms we can say, == operator only checks for value and not for
type
Some examples of ==
"1" == 1; // true
1 == "1"; // true
0 == false; // true
0 == null; // false
0 == undefined; // false
0 == !!null; // true, look at Logical NOT operator
0 == !!undefined; // true, look at Logical NOT operator
null == undefined; // true
const number1 = new Number(3);
const number2 = new Number(3);
number1 == 3; // true
number1 == number2; // false
const object1 = {
key: "value",
};
const object2 = {
key: "value",
};
console.log(object1 == object2); // false
console.log(object1 == object1); // true
Strict Equality operator ๐๐ป ===
The strict equality operator compares value of operands but it doesn't attempt type conversion on both the operands to a common type. In layman terms we can say, === operator checks both for value as well as for
type
Some examples of ===
"3" === 3; // false
true === 1; // false
null === undefined; // false
3 === new Number(3); // false
const object1 = {
key: "value",
};
const object2 = {
key: "value",
};
console.log(object1 === object2); // false
console.log(object1 === object1); // true
By using two different equality operators, JavaScript manages loose and strong type-checking.