JavaScript Comparison and Logical Operators
8 April 2025 | Category: JavaScript
JavaScript provides comparison operators to compare values and logical operators to combine multiple conditions.
These are widely used in if statements, loops, and any kind of decision-making logic.
🔍 Comparison Operators
Comparison operators compare two values and return a Boolean (true
or false
).
Operator | Description | Example | Result |
---|---|---|---|
== | Equal to | 5 == "5" | true |
=== | Equal value and type | 5 === "5" | false |
!= | Not equal to | 5 != 3 | true |
!== | Not equal value or type | 5 !== "5" | true |
> | Greater than | 10 > 5 | true |
< | Less than | 10 < 5 | false |
>= | Greater than or equal to | 10 >= 10 | true |
<= | Less than or equal to | 5 <= 3 | false |
Example:
console.log(7 == "7"); // true
console.log(7 === "7"); // false
console.log(5 > 3); // true
console.log(5 < 3); // false
đź”— Logical Operators
Logical operators are used to combine multiple Boolean conditions.
Operator | Name | Description |
---|---|---|
&& | AND | True if both conditions are true |
|| | OR | True if at least one is true |
! | NOT | Reverses the condition (true → false ) |
Examples:
let age = 20;
console.log(age > 18 && age < 25); // true (both true)
console.log(age > 25 || age < 30); // true (one is true)
console.log(!(age > 18)); // false (negates true)
đź§Ş Real-World Example
let isLoggedIn = true;
let hasPermission = false;
if (isLoggedIn && hasPermission) {
console.log("Access granted");
} else {
console.log("Access denied");
}
Output:
Access denied
⚠️ Equality vs Strict Equality
==
allows type conversion===
checks both value and type (more strict)
5 == "5" // true
5 === "5" // false
đź§ Summary
- Comparison operators compare values and return Boolean.
- Logical operators combine conditions.
- Use
===
for safer comparisons (no type conversion). &&
,||
, and!
are key tools for decision-making.