Unlike other languages JavaScript has two ways to determine equalities. It can be rather confusing for people like myself who come from typed languages like Java or C++. My goal is to explain both == and === in a clear and concise manner through definition and examples.
TRIPE EQUALS (STRICT EQUALITY)
The triple equals compares the two values for equality. No extra work is done, it simply checks if the both values have the same type and if they do it then checks whether the two values are the same. If the types are not the same it returns false. If the the types are the same, but the values are different it returns false. Here are some examples:
7 === 7 //true
7 === '7' // false
DOUBLE EQUALS (LOOSE EQUALITY)
The double equals comparison works by first converting the both values to a common type and then undergoing a strict comparison as === does. Let's look at an example to make the explanation a bit more comprehensible. The code below is comparing a Number and a String. The double equals comparison first converts both values to a common type (in this case a Number) and then runs a strict comparison (i.e., it checks if 17 and 17 are the same type and are equal which is true since in the previous step it converted both values to Number).
17 == '17' // true
17 == 17 // true
CLOSING
It's hard to forget the difference between the two. With that being said, I recommend you write code that allows you to use triple equals rather than double equals. Using double equals can cause unwanted conversions producing inaccurate results.
Top comments (1)
Good explanation.
But triple equals mainly checks the equality between objects like left side and right side both are referring to the same object or not.
For example,
Above code will return FALSE because both variable not referring to same object. Let's consider another example.
The above code will return TRUE because both left and right side referring to same object.