Difference Between "== " vs "===" in JavaScript

Difference Between "== " vs "===" in JavaScript

In JavaScript, there are couple of ways for checking equality. They might be do same exact thing, but there is one major difference between them which makes triple equal operator almost always better.

Let's declare two variables and compare them using both operators.

Screenshot (83).png

In the above example, we got the same answer i.e true. So, What's the difference?

Wait let's try this

Screenshot (85).png

Here, we are comparing an integer and string with the same value. In double equality we got an answer as true and in triple equality we got false .how this is possible?

Well because the '==' operator takes only value into consideration, not the data type. That means "==" operator first converts the variable values to the same type before performing the comparison whereas "===" operators does not have any conversion.

  • "==" operator is also knows as Loose equality comparison operator in JavaScript.

  • "===" operator is also knows as strict comparison operator in JavaScript.

let's take one more example with boolean value.

Screenshot (87).png As above stated, incase of double equals operator first its converting the values (a & b)in same type then performing comparison but incase of triple equals operator the values of a & b both are assuming differently as there is no type conversion.

Summary

  • "==" operator is value based comparison and "===" operator is value & data type based comparison operator.

  • "==" operators returns true only if two operands are equal while "===" returns true only if both values and data types are the same.

  • Most of the times we should use "===" operator instead of "==" operator as its more accurate & strict in comparison.

Thank You for Reading !