JavaScript Comparison and Logical Operators

Comparison and logical operators are fundamental tools for writing conditional statements and controlling the flow of your code. In JavaScript, there are seven comparison operators and three logical operators.

Comparison Operators

Comparison operators are used to compare two values and return a Boolean value (true or false). The following table summarizes the JavaScript comparison operators:

OperatorDescriptionExample
==Equal to (value and type)10 == 10 evaluates to true
===Strict equal to (value and type)10 === 10 evaluates to true, but 10 === "10" evaluates to false
!=Not equal to (value or type)10 != 10 evaluates to false, but 10 != "10" evaluates to true
!==Strict not equal to (value and type)10 !== 10 evaluates to false, but 10 !== "10" evaluates to true
<Less than10 < 15 evaluates to true
>Greater than15 > 10 evaluates to true
<=Less than or equal to10 <= 15 evaluates to true
>=Greater than or equal to15 >= 10 evaluates to true

Logical Operators

Logical operators are used to combine two or more Boolean expressions and return a single Boolean value. The following table summarizes the JavaScript logical operators:

OperatorDescriptionExample
&&Logical ANDtrue && true evaluates to true, but true && false and false && true evaluate to false
``Logical OR
!Logical NOT!true evaluates to false, and !false evaluates to true

Combining Comparison and Logical Operators

You can combine comparison and logical operators to create more complex conditional expressions. For example, the following expression evaluates to true only if the value of age is greater than or equal to 18 and the value of isCitizen is true:

(age >= 18) && isCitizen;

You can also use parentheses to group expressions and control the order in which they are evaluated. For example, the following expression evaluates to true only if the value of age is greater than 18 or the value of isCitizen is true:

(age >= 18) || isCitizen;

Examples

Here are some examples of how to use comparison and logical operators in JavaScript:

// Check if the value of `age` is greater than or equal to 18.
if (age >= 18) {
console.log("You are old enough to vote.");
} else {
console.log("You are not old enough to vote.");
}


// Check if the value of `age` is greater than or equal to 18 and the value of `isCitizen` is `true`.
if ((age >= 18) && isCitizen) {
console.log("You are eligible to vote.");
} else {
console.log("You are not eligible to vote.");
}


// Check if the value of `age` is greater than 18 or the value of `isCitizen` is `true`.
if ((age >= 18) || isCitizen) {
console.log("You are eligible to vote or to become a citizen.");
} else {
console.log("You are not eligible to vote or to become a citizen.");
}