You’re marvelling why that part of code inside an if block is being executed while you expected it to be glance right! Well, let’s easy and see what’s incident under the hood to understand why quite that is happening.
You’re awestruck why that piece of code inside an if block is being performed while you expected it to be fly right! Well, let’s try and see what’s happening bottom the hood to understand why strictly that is happening.
Javascript supports two types of equality operators:
- The Equality Operator(==) and
- The Strict Equality Operator (===)
The equality operator deal with the “types” of the operands being compared and applies some rules on the operands with honour to type conversion.
web zone
Two values are strictly equal only if they have the same type and the same value. We will focus on the equality operator in this post since, well, there’s not much to highlight with respect to the strict equality operator J.
I hope you are aware of the primitive data types in JavaScript:
- Boolean
- Strings
- Numbers
CASE1: HAVING THE SAME TYPE OF BOTH OPERANDS
This is the easiest case. If both the operands are of the same type, then compare their values. No type conversion required.
CASE 2: COMPARE A STRING AND A NUMBER
- The string is converted to a number.
- Does the string represent a valid number: Compare the values.
- The string does not have a valid number(NaN): Return false.
CASE 3: COMPARE A BOOLEAN TO A NUMBER
- Convert the Boolean to a number. True evaluates to 1, false evaluates to 0.
- Compare the values.
CASE 4: COMPARE A BOOLEAN TO A STRING
- Convert the Boolean to a number. True evaluates to 1, false evaluates to 0.
- Convert the String to a number.
- Compare the values.
CASE 5: COMPARE UNDEFINED TO NULL
Evaluates to true. Strange but true. Since both null and undefined represent “no value” (i.e. an object with no value and a variable with no value respectively.)
SOME RULES OF TYPE CONVERSION:
- The string” ” converts to 0
- Anything compared to NaN evaluates to False.
- Anything (except null) compared to Undefined evaluates to False.