Logical Operators

Javascript has the following comparison operators:

  • && and
  • || or
  • ! not

The logical operators work normally when their operands are boolean expressions, that is, for instance, x && y will return true if both x and y evaluate to true. It will also employ short-circuiting and will not evaluate y if x evaluates to false.

const isCitizen = true;
const age = 28;
console.log(isCitizen && age > 64); 

Let's revisit the earlier statement:

The logical operators work normally when their operands are boolean expressions.

What if their operands are not boolean expressions? Hmm, you may be thinking the operands are probably converted to boolean and then ... let me stop you right there. Embrace yourself for madness!

JavaScript && and || operators actually don't return a boolean!! They always return one of their operands! If the operands happened to be booleans, then it looks like everything works normally. But things get weird when one or more operand are not boolean!

Here is what really happens:

x && y: If x can be converted to true, returns y; else, returns x

console.log(true && "Ali"); 
console.log(false && "Ali"); 

x || y: If x can be converted to true, returns x; else, returns y

console.log(true || "Ali"); 
console.log(false || "Ali"); 

The JavaScript community has (perhaps unfortunately) embraced these features. 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!)

For a more in-dept consideration of logical operators, read Aashni's "Lazy Evaluations and Short Circuit Logic in Javascript"