Basic Relational Comparison
<=(less than or equal to)
>=(greater than or equal to)
console.log(1 < 2); // true console.log(2 >= 1); // true
console.log("a" < "b"); // true console.log("b" > "a"); // true
Equality Comparison (==)
==) operator, which compares two values for equality. It converts the operands to the same type before making the comparison. For example:
console.log(1 == "1"); // true console.log(true == 1); // true
In the first example, the number 1 is compared to the string
true. In the second example, the boolean value
true as well.
Strict Equality (===)
console.log(1 === "1"); // false console.log(true === 1); // false
In contrast to the equality comparison, the strict equality comparison returns false in the above examples because the operands have different types.
Type Coercion Comparison
typeof operator returns a string indicating the type of the operand, and can be used in the following ways:
console.log(typeof "hello world"); // "string" console.log(typeof 42); // "number" console.log(typeof true); // "boolean" console.log(typeof undefined); // "undefined" console.log(typeof null); // "object"
Comparing Different Types
Note that the comparison may not always return the expected result. Here's a similar example of comparing a number and a string:
console.log("5" == 5); // true console.log("5" === 5); // false
5 == 5 which is true. In the second example, the strict equality operator
"5" === 5 which is false.
Another example is when comparing a boolean with a number:
console.log(0 == false); // true console.log(0 === false); // false
false to a number
0 before making the comparison, resulting in
0 == 0 which is true. In the second example, the strict equality operator
0 === false which is false.
Nuanced Cases with
NaNis a special value that represents "not a number." It is the result of an undefined or unrepresentable mathematical operation. However, when using the strict equality operator (
NaNwill not equal any other value, including itself. Instead, you must use the built-in function
isNaN()to check for
nullare considered to be loosely equal to each other when using the equality operator (
==). But they are not strictly equal (
===) to any other value.
undefined values can be encountered when trying to access properties or variables that have not been defined, or have been declared but have not been assigned a value.