Episode 16 of 46
Logical Operators in JavaScript
Learn AND, OR, NOT operators to combine conditions in your code.
Logical operators let you combine multiple conditions into a single expression.
AND (&&)
Returns true only if both conditions are true:
let age = 25;
let hasLicense = true;
if (age >= 18 && hasLicense) {
console.log("You can drive!");
}
// Truth table:
// true && true → true
// true && false → false
// false && true → false
// false && false → false
OR (||)
Returns true if at least one condition is true:
let day = "Saturday";
if (day === "Saturday" || day === "Sunday") {
console.log("It's the weekend!");
}
// Truth table:
// true || true → true
// true || false → true
// false || true → true
// false || false → false
NOT (!)
Flips a boolean value:
let isLoggedIn = false;
if (!isLoggedIn) {
console.log("Please log in.");
}
console.log(!true); // false
console.log(!false); // true
console.log(!""); // true (empty string is falsy)
console.log(!"hello"); // false (non-empty string is truthy)
Combining Operators
let age = 25;
let isStudent = true;
let hasID = true;
if ((age >= 18 && hasID) || isStudent) {
console.log("Access granted!");
}
Short-Circuit Evaluation
// && returns the first falsy value (or the last value)
let name = "" && "Alice"; // "" (empty string is falsy)
// || returns the first truthy value (or the last value)
let user = "" || "Guest"; // "Guest"
let port = undefined || 3000; // 3000