Browse All Articles
The equality operator is denoted as “==” while strict equality operator is denoted as “===”.
Equality operator: (==)
This comparison operator returns true only when they are equal without comparing their types.
true == 1; //true, because 'true' is converted to 1 and then compared.
"2" == 2; //true, because 2 (the integer) is converted to "2" (the string) and then compared.
Strict equality operator: (===)
You can use this operator only when exact type of operand is important for comparison.
true === 1; //false
"2" === 2; // false
2. If one of the operands is Boolean, the Boolean operand is converted to 1 if it is true and +0 if it is false.
4. If both operands are objects, they're compared as objects and the equality test is true only if both refer the same object.
If we consider theoretically, because strict equality operator (===) does not do conversion for comparison is faster than == operator.
Now let us execute below programs and we will calculate the time for their execution:
var n = 0;
Here are results: (averaged):
var n = 0;
For the first one (i.e. for == operator): 24 ms
For the second one (i.e. for === operator): 26 ms
If you see the total time required to execute for both comparisons, for over 100000 iterations, the difference is very less.
So strict equality operator (===) should be used for type safety and code equality reason, 'performance' should not the reason to use.
Finally here are some examples:
alert('' == '0'); // false
alert(0 == ''); // true
alert(0 == '0'); // true
alert(false == 'false'); // false
alert(false == '0'); // true
alert(false == undefined); // false
alert(false == null); // false
alert(null == undefined); // true
alert(' \t\r\n ' == 0); // true
For strict comparison (using === ) for above all examples, results into false.
It is recommended to use strict equality operator(===), when one has to perform comparison with type check.