Uncover the distinction between == and === that may still be unfamiliar to you!
When inquiring about the dissimilarity between == and ===, most individuals will assert that == performs loose type checking, while === involves both type and value checking.
This doesn't capture the entire truth.
This is utterly incorrect. β
==, or abstract equality, performs type checking as its primary function. In fact, the initial action of == is to conduct type-checking.
What distinguishes == (Abstract Equality) from === (Strict Equality)?
Let's discover together.
== (Abstract Equality) performs four distinct actions when comparing two variables, a
and b
.
1. Check the datatype of each variable.
If the types of both 'a' and 'b' are identical, perform a strict equality check and return the result.
1 == 1; // Internally return 1 === 1
2. Verify the absence of null and undefined.
If
a
isnull
andb
isundefined
, returntrue
If
a
isundefined
andb
isnull
, returntrue
null == undefined; // true
undefined == null; // true
3. Converting Non-Primitives to Their Primitive Form
When comparing non-primitive types such as Objects and arrays using the == (Abstract Equality) operator, they are initially converted to their non-primitive counterparts by invoking the toString() method.
[] == ""; // [ ] will be converted into a string
[].toString() == "";
"" == ""; // true
4. Convert to Number
If the variable
a
is of the Number type, convert variableb
to Number by encapsulating it within a Number function call, and subsequently compare the outcomes.Conversely, if the variable
b
is of the Number type, convert variablea
to Number by encapsulating it within a Number function call, and then compare the results.
"1" == 1; // "1" will be converted into Number
Number("1") == 1
1 == 1 // true
Observing the steps above leads to the conclusion that ==(Abstract Equality) involves type coercion during variable comparison, whereas ===(Strict Equality) does not perform any type coercion.
This constitutes the fundamental distinction between == and ===.
Happy Coding! π
And donβt forget to find me on the web: https://linktr.ee/AliSamir π
Top comments (0)