The Javascript Equality Operator
You’re wondering why that piece of code inside an if block is being executed while you expected it to be skipped, right? Well, let’s look at what’s happening under the hood to understand why exactly that is happening.
Join the DZone community and get the full member experience.
Join For FreeYou’re wondering why that piece of code inside an if block is being executed while you expected it to be skipped, right?
Well, let’s look at what’s happening under the hood to understand why exactly that is happening.
Javascript supports two types of equality operators:
The equality operator considers the "types" of the operands being compared and applies some rules on the operands with respect to type conversion.
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 article 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: Both Operands of the Same Type
This is the simplest 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.
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.
Operand Type | Boolean | String | Numbers | NAN/Undefined |
Boolean | True if both the operands have the same value | Convert the string to a number if possible and then compare | Convert Boolean to number and compare. True evaluates to 1 and false evaluates to 0 | False |
String | Convert Boolean to number and compare. True evaluates to 1 and false evaluates to 0 | True if both the operands have the same value | Convert the string to a number if possible and then compare | False |
Numbers | Convert Boolean to number and compare. True evaluates to 1 and false evaluates to 0 | Convert the string to a number if possible and then compare | True if both the operands have the same value | False |
Opinions expressed by DZone contributors are their own.
Comments