In this chapter, we will learn about JavaScript logical operators. These operators are used to combine multiple boolean expressions and return a boolean value (true
or false
). We will cover:
- Logical AND (&&)
- Logical OR (||)
- Logical NOT (!)
Logical AND (&&)
The logical AND operator returns true
if both operands are true
. Otherwise, it returns false
.
Syntax
expression1 && expression2;
Example
let a = true;
let b = false;
let result = a && b;
console.log(result); // Output: false
result = a && true;
console.log(result); // Output: true
Short-Circuit Evaluation
If the first operand is false
, the logical AND operator will not evaluate the second operand because the result will always be false
.
Example
let x = 5;
let y = 10;
let result = (x > 10) && (y < 20); // x > 10 is false, so y < 20 is not evaluated
console.log(result); // Output: false
Logical OR (||)
The logical OR operator returns true
if at least one of the operands is true
. Otherwise, it returns false
.
Syntax
expression1 || expression2;
Example
let a = true;
let b = false;
let result = a || b;
console.log(result); // Output: true
result = b || false;
console.log(result); // Output: false
Short-Circuit Evaluation
If the first operand is true
, the logical OR operator will not evaluate the second operand because the result will always be true
.
Example
let x = 5;
let y = 10;
let result = (x < 10) || (y > 20); // x < 10 is true, so y > 20 is not evaluated
console.log(result); // Output: true
Logical NOT (!)
The logical NOT operator returns true
if the operand is false
and false
if the operand is true
. It inverts the boolean value of its operand.
Syntax
!expression;
Example
let a = true;
let result = !a;
console.log(result); // Output: false
result = !false;
console.log(result); // Output: true
Combining Logical Operators
Logical operators can be combined to form complex logical expressions.
Example
let x = 5;
let y = 10;
let z = 15;
let result = (x < y) && (y < z) || (x > z);
console.log(result); // Output: true
result = !(x < y) || (y > z);
console.log(result); // Output: false
Conclusion
In this chapter, you learned about JavaScript logical operators, including logical AND, logical OR, and logical NOT. These operators are essential for combining boolean expressions and making decisions in your code. Understanding how to use logical operators will help you write more complex and efficient conditional statements. In the next chapter, we will explore JavaScript bitwise operators and how to use them in your programs.