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 will return true if both x and y evaluate to true. The operator will also employ short-circuiting; it 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!

The JavaScript && and || operators 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 as expected. But things get weird when one or more operands 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 && "Cao"); 
console.log(false && "Cao"); 

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

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

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!)

Resources