Equality Operators
In this lesson, we'll see the significance and usage of the equality operators in JavaScript. Let's begin!
Equality
Testing equality is an important operation in every programming language, just like in JavaScript.
Due to the loosely-typed nature of JavaScript, it defines two kinds of equality:
- identically equal (
===
), and - equal (
==
)
Non-Equality
Implicitly, there are two kinds of non-equality:
- not identically equal (
!==
), and - not equal (
!=
)
The equal and not equal operators use conversion to determine the equality of their operands.
Rules for conversions
During the conversion they follow these rules:
- If an operand is a
Boolean
value, it is converted into aNumber
before checking for equality. A value of false is converted to 0, whereas a value of true is converted to 1. - If one operand is a string and the other is numeric, before testing, the string value is attempted to be converted into a
Number
. - If one of the operands is an object and the other is not, the
valueOf()
method is called on the object to retrieve a primitive value to compare according to the previous rules.
Rules for comparisons
When making the comparisons, operators follow these rules:
- Values of null and undefined are equal.
- Values of null and undefined cannot be converted into any other values for equality checking.
- If either operand is NaN, the equal operator returns false and the not-equal operator returns true.
- If both operands are objects, then they are compared to see if they are the same object. If both operands point to the same object, then the equal operator returns true; otherwise, false, because they are not equal.
Examples
Let’s look at a few examples:
console.log(null == undefined); // trueconsole.log(23 == "23"); // trueconsole.log(1 / 0 == 2 / 0); // trueconsole.log(false == 0); // trueconsole.log(true == 1); // trueconsole.log(true == 2); // falseconsole.log(NaN == NaN); // false
📜NOTE: As it was already treated earlier,
NaN
is a special value that is not equal to itself.
The identically equal and not identically equal operators do not convert the operands before testing for equality. The two operands are identically equal if and only if their types and their values are equal.
These short examples demonstrate how they work:
console.log(23 == "23"); // trueconsole.log(23 === "23"); // falseconsole.log(23 === (12 + 11)); // trueconsole.log(23 != "23"); // falseconsole.log(23 !== "23"); // true
Quiz Time!
Question 1
Given the following expression:
800 === "800"
What value will be returned?
true
false
Question 2
Given the following expression:
800 == "800"
What value will be returned?
true
false
In the next lesson, we’ll see the capabilities of the relational and Boolean operators.
Stay tuned!