Equality operators in Javascript (== vs ===)

The equality operator in javascript will return a boolean value that is either true or false just like any other comparison operator in javascript. Javascript has two kinds of equality operators.

  1. Loose equality operator( == )
  2. Strict equality operator ( === )

Loose equality operator

The loose equality operator will return true when the operands are equal and of same data type, and also when the operands are equal and of different data type.

const age = '18';

// loose equality operator  is implemented
if(age == 18)
{
  console.log("You are eligible to vote! Congrats.");
}
else
{
  console.log("You are not eligible to vote yet");
}

In the above code snippet, the equality operator results in true and the if block is executed despite the age variable containing a string and being compared for equality to a number.Here the concept of type coercion comes into play. Here the loose equality operator performs types coercion where the operands are implicitly converted to the same data type before the comparison occurs.Javascript here considers the variable age which contains a string and the number 18 to be of same data type. Hence we get the result as true in this case.

Let us consider another code snippet,

const age = 18;

// loose equality operator  is implemented
if(age == 18)
{
  console.log("You are eligible to vote! Congrats.");
}
else
{
  console.log("You are not eligible to vote yet");
}

In the above code snippet too we get the result of the comparison operator as true and therefore the if block is executed.

Strict equality operator

The strict equality operator will return true if and only when the operands are equal and are also of the same data type.

// age is initialised to 18 as a string 
const age = '18';

// Strict equality operator is implemented
if(age === 18)
{
  console.log("You are eligible to vote! Congrats.");
}
else
{
  console.log("You are not eligible to vote yet");
}

The above example will return "You are not eligible to vote yet" albeit 18 is indeed equal to 18. Here the age variable contains a string '18' , and it is tested for equality with 18 which is of data type number. Therefore you get the result as false which results in the else block being executed.

If we consider another example where the variable age contains 18 of data type number we get a different result.

// age is initialised to 18 as a number 
const age = 18;
if(age === 18)
{
  console.log("You are eligible to vote! Congrats.");
}
else
{
  console.log("You are not eligible to vote yet");
}

In the above code snippet the equality operator will yield the result as true because the variable age and the number 18 are of the same date type and also of the same value.

In the case of strict equality operator, javascript doesn’t perform type coercion.