JavaScript logical operators

bunnyju003/02/2025
andjavascirptor
JavaScript logical operators

There are three types of logical operators in JavaScript:

|| (OR), && (AND), and ! (NOT).

Let's go over each one.


|| (OR)


The 'OR' operator can be written using two vertical bars.

result = a || b;

In programming, the OR operator is usually used to work with Boolean values.

If at least one of the operands is true, it returns true; otherwise, it returns false.

Since the OR operator is a binary operator, there are four possible combinations:

alert( true || true ); // true 
alert( false || true ); // true 
alert( true || false ); // true 
alert( false || false ); // false

The result is always true except when both values are false.


If an operand is not a Boolean, it is converted to a Boolean for evaluation.

For example, in the operation, the number 1 is treated as true, and 0 is treated as false.

if (1 || 0) { 
  alert( 'truthy!' );
}

How to Use the OR Operator in JavaScript


Example 1: Multiple OR operators

result = value1 || value2 || value3;
  1. It starts from the leftmost operand and moves to the right, evaluating each operand.
  2. Each operand is converted to a Boolean. If the converted value is true, the evaluation stops and returns the original (non-converted) value of that operand.
  3. If all operands evaluate to false, the last operand is returned.



The key point here is that the returned value is the original, unconverted value.

Let's look at an example:

let firstName = "";
let lastName = "";
let nickName = "Violet";

alert( firstName || lastName || nickName || "Anonymous"); // Violet



&& (AND)


The AND operator && is written using two ampersands.

result = a && b;

In traditional programming, the AND operator returns true only when both operands are true. Otherwise, it returns false.

alert( true && true );  // true
alert( false && true ); // false
alert( true && false ); // false
alert( false && false ); // false




bunnyju0
bunnyju0View profile