Skip to main content

JavaScript Logical Operators (Live Playground)

Logical operators are used to evaluate complex expressions based on multiple conditions. They return a boolean result, either true or false, based on the outcome of the evaluation. In this tutorial, we'll explore the most commonly used logical operators in JavaScript and learn how to use them in our code.

AND Operator (&&)

The AND operator returns true if both operands are true, otherwise, it returns false.

Example:

const a = true;
const b = false;
console.log(a && b); // Output: false
Live Playground, Try it Yourself

OR Operator (||)

The OR operator returns true if at least one of the operands is true, otherwise, it returns false.

Example:

const a = true;
const b = false;
console.log(a || b); // Output: true
Live Playground, Try it Yourself

NOT Operator (!)

The NOT operator returns true if the operand is false, and false if the operand is true. It is used to invert the boolean value of an expression.

Example:

const a = true;
console.log(!a); // Output: false
Live Playground, Try it Yourself

Combining Logical Operators

Logical operators can be combined to create more complex expressions.

Example:

const a = 10;
const b = 20;
const c = 30;

if (a < b && b < c) {
console.log('Both conditions are true');
} else {
console.log('At least one condition is false');
}

In the example above, the output is 'Both conditions are true' because both a < b and b < c are true.

Live Playground, Try it Yourself

Conclusion

Understanding and using logical operators is crucial for evaluating complex expressions and making decisions in your JavaScript programs. Familiarize yourself with the basic logical operators, such as AND, OR, and NOT, to create more intricate conditions and control the flow of your code.