Equality operator (==) compares two values after all necessary type conversions. Let’s take a look at a few examples:
0 == '' // -> true false == 'false' // -> false
In the first example both 0 and ‘’ (empty string) undergo automatic conversion. They are both converted to false giving:
false == false
Which is obviously true. In the second example ‘false’, a non-empty String is evaluated to true making the whole expression false.
In comparison, identity operator (===) will return true if and only if both values that are being compared are of the same type and have the same value. If we try to compare values of two different types, it will always return false.
false === 0 // -> false 0 === '' // -> false 5 === 5 // -> true
To be precise, === checks whether two variables reference the same object, or in case of value types (like int, double, String, bool, etc.) if they both have the same value.
var array1 = [ 5, 6, 7 ]; var array2 = [ 5, 6, 7 ]; var array3 = array2; array1 === array2 // -> false array1 == array2 // -> false array2 === array3 // -> true array2 == array3 // -> true
Both array1 and array2 have the same type and they are equal but comparison array1 === array2 returns false as they refer to different objects. array2 === array3 returns true as both variables refer to the same object.
Which operator should I use?
It’s important to understand the difference between == and === but which operator should be used?