Why you shouldn't use Double Equals Operator in JavaScript

Why you shouldn't use Double Equals Operator in JavaScript

ยท

2 min read

Unlike many other programming languages JavaScript has both double equals '==' and triple equals '===' comparison operator. They might seem to do the same exact thing, but there is one major difference between the two that makes triple equals almost always better.

What's the Difference?

The '==' Operator

This is called Loose equality comparison operator in JavaScript.

Let's take an example here when comparing a string and an integer with the same value.

let a=1;
let b='1'; 
console.log(a==b);

OUTPUT

true

or wait let's try this

let a=1;
let b=true; 
console.log(a==b);

OUTPUT

true

https://cdn.hashnode.com/res/hashnode/image/upload/v1599030905638/ChglLb-z-.jpeg

WHAT?? How is it true??

You may be wondering how this is possible? well because the '==' operator takes only value into consideration, not the type. Therefore matches boolean true to 1 by converting one of them.

The '===' Operator

This is called Strict equality comparison operator in JavaScript.

let a=1;
let b='1'; 
let c=true;
console.log(a===b);
console.log(a===c);
false
false

This returns false for the values which are not of a similar type. This operator performs type casting for equality. If we compare 1 with '1' using ===, then it will return a false value.

When to use the '==' Operator

I don't usually recommend to use this often but you can use this when

  • Checking if a value is null/undefined
  • When you know both the operators of the same type

To Summarize

  • '==' Operator is Value based comparison

  • '===' Operator is Type+Value based comparison

So most of the times you should be using triple equals insead of double equals as it's more precise, accurate and doesn't bring up bugs which are not easy to find.


I love speaking to new people on the internet. Hit me up on Twitter or Linkedin , Lets talk tech.

hrithwik.jpg