Learning JS: Equality in Javascript

Anupam Srivastava
2 min readAug 18, 2021

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:

Type coercion example

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.

Example

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:

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.

Sign up to discover human stories that deepen your understanding of the world.

Free

Distraction-free reading. No ads.

Organize your knowledge with lists and highlights.

Tell your story. Find your audience.

Membership

Read member-only stories

Support writers you read most

Earn money for your writing

Listen to audio narrations

Read offline with the Medium app

Anupam Srivastava
Anupam Srivastava

Written by Anupam Srivastava

0 Followers

developer, tech enthusiast

No responses yet

Write a response