Understanding "Equality Operators" in JavaScript

Understanding "Equality Operators" in JavaScript

Equality is the thing, that everyone strives for in this modern age but still there remains some amount of it in JavaScript. Let's learn about equality operators in JavaScript.

There are two broad types of equality operators in JavaScript.

  1. Loose Equality : ( "==" i.e. Double equals )

  2. Strict Equality : ( "===" i.e. Triple equals )

Both are used to compare the degree of equality between the things concerned.

Let's look at them one by one

Loose Equality :

Loose equality aka double equals converts types of two things under comparison into a common one if they differ. Then it makes a value comparison.

Let's understand with the help of the example,

In the above example, the type of "27" value for the variable "ageOfOmkar" is "Number" whereas the type of "27" value for the variable "ageOfOmkarString" is "String".

When we test the Loose equality of the two variables by invoking a function named, "ageComparison" , at an initial stage, the javaScript engine is converting both the types into a common one and the testing equality of their values. As the values for both variables are the same it shows the output as true.

Rules for type conversions:

  • If either operand is a string, the other operand will be converted to a string.

  • If either operand is a number, the other operand will be converted to a number.

  • If either operand is a boolean, it will be converted to a number (true becomes 1 and false becomes 0).

  • If one operand is an object and the other is a primitive value, the object will be converted to a primitive value before the comparison is made.

  • If one of the operands is null or undefined, the other must also be null or undefined to return true. Otherwise, it will return false.

Hence for loose equality, the value of the variables plays an important role over types of variables.

Strict Equality :

Strict equality compares two values along with their types in equality. Unlike Loose equality testing, it does not convert types of variables into the common one. If the values have different types, the values are considered unequal. If the values have the same type and have the same value, they're considered equal.

Let's understand with the help of the example,

In the above example, for the first case, when we are giving 10 as input but with different types i.e number and string, then it is giving output as false. Even though their values are equal but their types are different and as strict equality does not do type conversion before comparison, Hence it shows the output as false.

In the second case, the values, as well as types of inputs, are the same, hence we are getting output as true.

To avoid getting undesired results or as a best practice, it is always recommended to use strict equality operator ( "===" ) in programming.