JavaScript Equality Comparison Algorithm
Are you sure you know about the equal-to operator (==)?
--
The equal-to operator seems to be a very simple concept, but in practice, it does a lot of manipulation in the background.
This article is focused around understanding the basic underlying concepts which lead to the manipulation of equality. We’ll consider the following scenarios:
- Comparing values of distinct types
- Equating a secondary object type with a primitive value
- Comparing null vs. undefined vs. falsy values.
- Type conversions during equality checks
We will look into multiple aspects of comparing two values using the equal-to operator (==
). While comparing two variables, we also need to consider the concept of type conversion.
Getting Started
Ever wondered what happens behind the scenes when you compare the values of different types of example comparison of objects with numeric values? Let’s look into these details.
When we perform the operation x == y
, it always returns either true or false. However, with comparison, the following could be the scenarios possible …
Comparison between same types: ( Type(x) == Type(y) )
When we compare the value of variables of the same type, it is comparatively an easier win. We need not analyze a lot in order to compare the variables of the same type.
Below we will look for the simple comparisons with the same type, and then we will extend the document to compare values of different types.
- If both
Type(x) == Type(y) == “undefined”
, then the output istrue
.
2. When Type(x) == Type(y) == “null”
, the output is true
.
3. If Type(x) == Type(y) == “String”
, the comparison will return true
if x
and y
are the exact sequences of characters and have the same length for values contained in the string.
4. If Type(x) == Type(y) == “Boolean”
, it will return true
if both values are either true
or false
, and it will return false
if both values are not the same.