In this article I will discuss about the equality operators == , != and Identically equality operator ===, !==.
JavaScript Coalescing
JavaScript works on the principle of coalescing where the language tries to coalesce the values or converts the values to most suitable form while performing some operations like addition of string and number as shown in below code.
In the above code snippet, the result is “12 12” instead of 24 as JavaScript has coalesced the the numeric 12 to string and displayed the result and same is true for the string and Boolean concatenation. Understanding this coalescing mechanism is important to understand how the equality comparison works in Javascript.
Equality/Not Equality (==, !=)
While doing the equality comparison using the == and != operators, JavaScript takes coalescing into consideration i.e. it does not take the type conversion into consideration and just compares the values as shown in the below code snippet.
In first three examples the result is true irrespective of the operands for which the operators are being used.
Identically Equality Operator(===, !==)
=== and !== does takes the type of the operands into consideration while doing equality comparison. Its same as concept of .Equals() method for object type in the way that it takes the type into consideration while doing comparison.
I have replaced the equality operator by identical equality operator from the above code snippet and we can see that the results are different for third case and forth case
You can know about where to write javascript code in my previous article.
Leave a Reply