Logical Operators
JavaScript has the following logical operators:
&&and||or!not
The logical operators work as expected when their operands are boolean expressions. For instance, x && y evaluates as truthy if both x and y evaluate to true. The operator also short-circuits; it does not evaluate y if x evaluates to false.
const isCitizen = true;
const age = 28;
console.log(isCitizen && age > 64); // false
Let’s revisit the earlier statement:
What if their operands are not boolean expressions? You might expect the operands to be converted to boolean values first, but JavaScript does something different.
The JavaScript && and || operators do not return a boolean. They always return one of their operands.
This is what actually happens:
console.log(true && "Ali"); // Ali
console.log(false && "Ali"); // false
console.log(true || "Ali"); // true
console.log(false || "Ali"); // Ali
JavaScript programmers rely on this behavior. You will find expressions such as
DEBUG && console.log("Some debugging message");
which is a short form of
if (DEBUG) {
console.log("Some debugging message");
}
The variable DEBUG is presumably a boolean value, but it does not have to be. (See the next section!)