JavaScript Comparison Operators
Comparison operators in JavaScript are used to compare values and return a boolean result (true
or false
). These operators help in making decisions based on conditions. Here’s a detailed look at each comparison operator:
1. Equality (==
)
- Purpose: Checks if two values are equal, performing type coercion if necessary.
- Example:
let a = 5; let b = '5'; console.log(a == b); // true, because '5' is coerced to a number
2. Strict Equality (===
)
- Purpose: Checks if two values are equal without performing type coercion.
- Example:
let a = 5; let b = '5'; console.log(a === b); // false, because the types are different
3. Inequality (!=
)
- Purpose: Checks if two values are not equal, performing type coercion if necessary.
- Example:
let a = 5; let b = '5'; console.log(a != b); // false, because '5' is coerced to a number
4. Strict Inequality (!==
)
- Purpose: Checks if two values are not equal without performing type coercion.
- Example:
let a = 5; let b = '5'; console.log(a !== b); // true, because the types are different
5. Greater Than (>
)
- Purpose: Checks if the value on the left is greater than the value on the right.
- Example:
let a = 10; let b = 5; console.log(a > b); // true
6. Less Than (<
)
- Purpose: Checks if the value on the left is less than the value on the right.
- Example:
let a = 3; let b = 7; console.log(a < b); // true
7. Greater Than or Equal To (>=
)
- Purpose: Checks if the value on the left is greater than or equal to the value on the right.
- Example:
let a = 5; let b = 5; console.log(a >= b); // true
8. Less Than or Equal To (<=
)
- Purpose: Checks if the value on the left is less than or equal to the value on the right.
- Example:
let a = 4; let b = 5; console.log(a <= b); // true
Key Points:
- Type Coercion: With
==
and!=
, JavaScript performs type coercion, meaning it tries to convert and compare values. For instance,0 == false
istrue
becausefalse
is coerced to0
. - Strict Comparison:
===
and!==
do not perform type coercion. They check both value and type. For example,0 === false
isfalse
because they are of different types. - NaN Comparisons:
NaN
is not equal to any value, including itself. So,NaN === NaN
isfalse
. UseNumber.isNaN()
to check forNaN
.