Skip to content

JavaScript logical operators | Basics

  • by

JavaScript has four logical operators: || (OR), && (AND), ! (NOT), ?? (Nullish Coalescing). Logical operators are used to determining the logic between variables or values.

&&and(x < 10 && y > 1) is true
||or(x == 5 || y == 5) is false
!or!(x == y) is true

JavaScript logical operators

A simple example code compares variables and does something based on the result of that comparison.

The Logical AND operator (&&)

The double ampersand (&&) to represent the logical AND operator. The following truth table illustrates the result of the && operator when it is applied to two Boolean values:

aba && b


<!DOCTYPE html>
    console.log( true && true );   
    console.log( false && true );  
    console.log( true && false );  
    console.log( false && false );



JavaScript logical operators

The Logical OR operator (||)

The doubles pipe || represents the logical OR operator. You can apply the || operator to two values of any type.

The following truth table illustrates the result of the || operator based on the value of the operands:

aba || b


console.log( true || true );   // true
console.log( false || true );  // true
console.log( true || false );  // true
console.log( false || false ); // false

The Logical NOT operator (!)

The exclamation point! represents the logical NOT operator. The ! operator can be applied to a single value of any type, not just a Boolean value.

The operator accepts a single argument and does the following:

  1. Converts the operand to boolean type: true/false.
  2. Returns the inverse value.
alert( !true ); // false
alert( !0 ); // true

The logical ! the operator works based on the following rules:

  • If a is undefined, the result is true.
  • If a is null, the result is true.
  • If a is a number other than 0, the result is false.
  • If a is NaN, the result is true.
  • If a is null, the result is true.
  • If a is an object, the result is false.
  • If a is an empty string, the result is true. In the case a is a non-empty string, the result is false
console.log(!undefined); // true
console.log(!null); // true
console.log(!20); //false
console.log(!0); //true
console.log(!NaN); //true
console.log(!{}); // false
console.log(!''); //true
console.log(!'OK'); //false
console.log(!false); //true
console.log(!true); //false

Do comment if you have any doubts or suggestions on this Js operator topic.

Note: The All JS Examples codes are tested on the Firefox browser and the Chrome browser.

OS: Windows 10

Code: HTML 5 Version

Leave a Reply

Your email address will not be published. Required fields are marked *