Language: EN

javascript-operadores-logicos

Logical Operators in JavaScript

Logical operators in JavaScript allow us to work with boolean values (true or false) and perform comparison and combination operations of conditions.

The most common logical operators are && (AND), || (OR), and ! (NOT), which allow us to build more complex logical expressions.

The following table presents the logical operators in JavaScript:

OperatorNameDescription
&&ANDReturns true if both operands are true
||ORReturns true if at least one of the operands is true
!NOTNegates the value

If you want to learn more about Logical Operators
check out the Introduction to Programming Course read more ⯈

List of logical operators

AND Operator (&&)

The AND operator && returns true if both combined expressions are true, and false otherwise.

const x = 5;
const y = 10;

if (x > 0 && y > 0) {
  console.log('Both variables are positive');
} else {
  console.log('At least one variable is not positive');
}

In this example, the expression x > 0 && y > 0 evaluates whether both x and y are greater than zero. If both conditions are true, the message “Both variables are positive” will be printed to the console.

OR Operator (||)

The OR operator || returns true if at least one of the combined expressions is true, and false if both are false.

const age = 25;

if (age < 18 || age > 65) {
  console.log('You have an age that can benefit from discounts');
} else {
  console.log('You do not qualify for age discounts');
}

In this example, the expression age < 18 || age > 65 evaluates whether the age is less than 18 or greater than 65.

If at least one of these conditions is true, the message “You have an age that can benefit from discounts” will be printed.

NOT Operator (!)

The NOT operator ! is used to invert the boolean value of an expression. If the expression is true, the NOT operator converts it to false, and vice versa.

const isRaining = false;

if (!isRaining) {
  console.log('You do not carry an umbrella');
} else {
  console.log('Take your umbrella with you');
}

In this example, !isRaining evaluates whether isRaining is false. If it is, the message “You do not carry an umbrella” will be printed, indicating that it is not necessary to carry an umbrella if it is not raining.

Combination of Logical Operators

We can combine multiple logical operators in the same expression to build more complex conditions.

const temperature = 25;
const rain = true;

if (temperature > 20 && !rain) {
  console.log('It is a good day to go for a walk');
} else {
  console.log('Better to stay at home');
}

In this example, the expression temperature > 20 && !rain evaluates whether the temperature is greater than 20 degrees and if it is not raining. If both conditions are true, the message “It is a good day to go for a walk” will be printed.