Learning JS: Equality in Javascript
I am sure you must have exclaimed when you first saw “===” instead of “==” somewhere while comparing two values in JS, well, I was too. Today I am going to tell you whats the reason behind it.
In JS we can compare two values using both “===” and “==”. But what’s the difference? Actually when we use “==”, the value is type coerced before the comparison and with “===” values are compared as it is.
Type coercion basically refers to the automatic or implicit conversion of value form one type to another. It is done by compiler on its own.
For eg:

Now coming back to equality :
== first checks the type of the two values and if they are not same it converts it to one type and then compares their types and values.
=== does not do type coercion and just compares the types and values and gives false if either of them is not same. Hence, called strict equality.

You must be wondering what’s the case in comparison of objects and arrays. Objects and arrays are compared differently in Javascript. Lets understand it using an example:

While comparing two objects Javascript checks whether they are pointing to the same object or not i.e if they have same reference. So x!==y because they are pointing to two different objects or memory locations whereas x=== z is true because they are pointing to same object. This type of equality is called reference equality. However, if we want to compare the contents of two objects-if they have same values or not - i.e. structural equality , Javascript does not have a built-in way to do that. We have to figure out something on our own or use third-party workarounds to check structural equality of objects.
This was all about equality in Javascript. Hope you find this blog helpful.
Thanks for reading. Please follow to get stories like this.