== and === in JavaScript
== Operator
The == operator converts the operands to the same type before checking for equality.
The == operator checks for the same value but not the same type of operands.
0 == false // true
2 == "2" // true
null == undefined // true=== Operator
The === operator does not perform any type conversion on the operands before checking for equality.
The === operator checks for both the same value and the same data type of the operands.
0 === false // false
2 === '2' // false
null === undefined // falseUsing the === operator is considered a best practice in JavaScript.
Questions
1. What will be the output of the following program?
console.log("location" == new String("location"));
console.log("location" === new String("location"));Answer — true, false
Explanation: In the first console statement, the == operator returns true because it converts both operands to the same type (string) and compares their values, which are equal.
In the second console statement, the === operator returns false because it performs a strict equality comparison, checking not only for the same value but also for the same data type. Since the left-hand operand is a string and the right-hand operand is an object (created using the new String() constructor), they are of different data types, resulting in a false comparison.