It is extremely confusing for them to understand in-depth difference and their use case. So let's get started with proper definitions and examples to grasp the core concept of "==" & "===".
In one word they both are comparison operators. They perform a comparison between their left & right operator and gives the result in
boolean (true or false) datatype.
Hold your coffee for a sec. Yes, both of them do the same but in a completely different method.
First of all, in simple terms "==" operator only checks the value which means it doesn't care which data types that the variable ar holding that's called a loose equality operator. For example:
const a = '1'; const b = 1; const c = a == b; console.log(c) //true
In the above example, variable a is string, and variable b number. Previously we said, "==" operator doesn't care about data types.
But actually behind the scene "==" operator does type conversion. If one operand's data type is string then before comparison "==" automatically converts the string datatype to number datatype. Hence, the example gives the output as
So, basically “===” operator returns
true if both operands are of the same data type and have the same value. Our first example gives different result for “===” operator. Take a look:
const a = 1; const b = '1'; const c = a === b; console.log(c) //false
const x = 0; const y = false; console.log(x == y) // true console.log(x == y) // false
The above example is another case of type conversion that is only done by the '"==" operator where '"===" leaves as it is. Here, we get
true for the '"==" operator because it converted 0 to
false. Even If we put string 0 it will also be converted to 0 no matter what.
In case of comparing
undefined, then the == operator will return true but the '"===" operator will return false:
const a = null; const b = undefined; console.log(a == b) //true console.log(a === b) // false
We can use the "==" operator where the user may enter data in both string and number format. (i.e: ‘1’ or 1) and our main concern is value is not a data type. On the other hand, we can use the "===" operator where the values are both data types must be the same and where
null/undefined may cause may lead us to an error.