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
is null andb
is undefined, return trueIf
a
is undefined andb
is null, return true
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 (2)
Some good examples, but.. to clarify and first thing first. The abstract equality operator is actually just called the equality operator. And numbers are converted to string underneath the hood at runtime. Besides that. Really nice post. π
The == only say that this 1 must be equal to 1 but can be diferent types. for example. if i put 1 and "1" will return true. with the 3 equals, must to be the same data type