JS Logical

JavaScript Logical Operators

Logical operators are typically used to combine multiple conditions or to reverse the logical state of an expression. They return a Boolean value (true or false) based on the outcome of the evaluation.

JavaScript supports the following logical operators:

Assume variable A holds 10 and variable B holds 20:

Operator Name Description Example
&& Logical AND If both the operands are non-zero, then the condition becomes true. (A && B) is true
|| Logical OR If any of the two operands are non-zero, then the condition becomes true. (A || B) is true
! Logical NOT Reverses the logical state of its operand. If a condition is true, then the Logical NOT operator will make it false. !(A && B) is false

1. Logical AND (&&)

The logical AND (&&) operator returns true if both operands (or conditions) are true. If either one of the operands is false, it returns false.

Logical AND Syntax

operand1 && operand2

Logical AND (&&) Example

let a = 10;
let b = 20;

if (a > 0 && b > 0) { console.log("Both numbers are positive."); } else { console.log("At least one number is not positive."); }


2. Logical OR (||)

The logical OR (||) operator returns true if at least one of the operands is true. It only returns false if both operands are false.

Logical OR Syntax

operand1 || operand2

Logical OR (||) Example

let a = 10;
let b = -5;

if (a > 0 || b > 0) { console.log("At least one number is positive."); } else { console.log("Neither number is positive."); }


3. Logical NOT (!)

The logical NOT (!) operator takes a single operand and reverses its logical state. If the operand evaluates to true, the ! operator returns false; if it evaluates to false, it returns true.

Logical NOT Syntax

!operand

Logical NOT (!) Example

let isRaining = false;

if (!isRaining) { console.log("It's a sunny day! No need for an umbrella."); } else { console.log("Take an umbrella."); }


Exercise

?

If A = 10 and B = 20, what is the result of !(A < 5 || B > 15)?