In JavaScript, comparison operators are used to compare two values in terms of equality, inequality, and relational comparisons. These operators evaluate the relationship between values and return a Boolean value (true
or false
) based on whether the comparison is true. Here's a list of the comparison operators in JavaScript:
-
Equal (
==
): Checks if the values of two operands are equal, performing type coercion if necessary.console.log(5 == '5'); // true
-
Not equal (
!=
): Checks if the values of two operands are not equal, performing type coercion if necessary.console.log(5 != '6'); // true
-
Strict equal (
===
): Checks if the values of two operands are equal, without performing type coercion (i.e., it also checks the type).console.log(5 === '5'); // false
-
Strict not equal (
!==
): Checks if the values of two operands are not equal, without performing type coercion.console.log(5 !== '5'); // true
-
Greater than (
>
): Checks if the value of the left operand is greater than the value of the right operand.console.log(5 > 3); // true
-
Greater than or equal to (
>=
): Checks if the value of the left operand is greater than or equal to the value of the right operand.console.log(5 >= 5); // true
-
Less than (
<
): Checks if the value of the left operand is less than the value of the right operand.console.log(3 < 5); // true
-
Less than or equal to (
<=
): Checks if the value of the left operand is less than or equal to the value of the right operand.console.log(5 <= 5); // true
Special Cases and Considerations
-
Type Coercion: The non-strict comparison operators (
==
and!=
) perform type coercion, meaning they convert the operands to the same type before making the comparison. This can sometimes lead to unexpected results. It's generally recommended to use the strict comparison operators (===
and!==
) to avoid issues related to type coercion. -
Comparing Different Types: When comparing values of different types, JavaScript converts the values to numbers. For example, when comparing a string to a number, the string is converted to a number if possible.
-
NaN Comparisons: The special value
NaN
(Not a Number) is considered unequal to any other value, including itself. To check if a value isNaN
, use theNumber.isNaN()
function instead of comparison operators.console.log(NaN == NaN); // false console.log(Number.isNaN(NaN)); // true
-
Comparing Objects: When comparing objects, the comparison is made based on reference and not the actual content of the objects. Two objects are considered equal only if they refer to the same instance.
let obj1 = {}; let obj2 = {}; let obj3 = obj1; console.log(obj1 == obj2); // false console.log(obj1 == obj3); // true