Equality operator and Strict equality operator in JavaScript
In JavaScript, there are various type of operators, here we are discussing about Equality operator (==) and Strict equality operator(===).
Equality operator (==) or Loose Equality:
This operator checks whether its two operands(value) are equal and return a Boolean (true or false) result. This operator is also convert operands that are of different types and then compare those operands.
For Example:
console.log(1 == 1);
// true
console.log(“3” == 3);
// true
console.log(“soni” == “soni”);
// true
console.log(NaN == NaN);
// false
console.log(0 == false);
// true
Strict equality operator (===):
The operator checks the equality of its two operands and returns a Boolean result. The strict equality operator always considers operands of different types to be different.
If operands are same type-
console.log(1 === 1);
// true
console.log(“help” === “help”);
// true
If operands are different type-
· if one operand is string and other one is number then returns false.
console.log(“1” === 1);
// false
· if both operands are objects then return true only if they refer to same object.
const object1 = {
name: “sohum”,
};
const object2 = {
name: “sohum”,
};
console.log(object1 === object2);
// false
console.log(object1 === object1);
// true
· if both operands are ‘null’ or ‘undefined’ then return true.
console.log(null === null);
// true
console.log(undefined === undefined);
// true
· if one of the operands is NaN then return false and this operator both operand +0 and -0 considered to be same value.
console.log(+0 === -0);
// true
References:
Neog Camp batch mates.