You are currently viewing Why I Strongly Recommend using Triple Equals in JavaScript

Why I Strongly Recommend using Triple Equals in JavaScript

Equality operator in Javascript

In this article, we will learn the equality operator in JavaScript. It is a slightly confusing topic to wrap your head around as a beginner. There are two types of equality:

  1. (==) double equals (allows coercion)
  2. (===) Triple equals (Does not allows coercion)

Let’s understand both with a few examples:

const var1='test';
const var2='test';
console.log(var1 == var2) //true
console.log(var1 === var2) //true
  • Here, we have created two constants namely “va1” and “var2”.
  • We assigned the same string value for both constants.
  • Then we console.log both equalities.
  • If we run the code both return true. When the types are the same there is no confusion.

However, if I change the var1 to a number and var2 to a string.

const var1= 10;
const var2='10';
console.log(var1 == var2) //true
console.log(var1 === var2) //false
  • You can see the above output, double equals are true whereas triple equals are false. In case of double equals JavaScript coerces the value to the same type. So, string 10 is converted into numeric 10 automatically and then compared. Both constants would be of the same value, hence the result is true.
  • Triple equals are more strict and ensure both constants must be of the same type and will not convert implicitly. Since a number is different from a string type, it returned false.

Now, it’s not wrong to use double equals but as a beginner, it is probably safe to use triple equals to check equality. And this is simply because there is quite a bit of strange coercion that JavaScript does. For example: if variable1 is equal to ‘0’ and variable2 is equal to an empty string.

const var1= 0;
const var2=' ';
console.log(var1 == var2) //true
console.log(var1 === var2) //false

You can see that double equals still returns true. As you can see may be confusing and lead to incorrect results. So, although it isn’t wrong to use double equals. My advice would be to use triple equals when writing code as a beginner. This concept of equality is very important.

Leave a Reply