JavaScript Basics

JavaScript Advanced

JavaScript Arrays

JavaScript Functions

JavaScript Objects

JavaScript DOM

JavaScript String

How to use Logical AND (&&) operator in JavaScript?

The double ampersand (&&) is used to represent Logical AND operator. It is a binary operator and expects two operands.

let result = operand1 && operand2;

Logical AND operator works in three ways:

1. Both operands are boolean values.

Logical AND operator returns true when both operands are true. If one or both operands is false, it returns false.

operand1 operand2 operand1 && operand2
true true true
true false false
false true false
false false false
let x = true,
    y = false;

console.log(x && y); //false

2. Both operands are relational expressions.

Logical AND operator returns true when both operands evaluates to true. If one or both operands evaluates to false, it returns false.

let number = 48;
let divisibleBySix = number%2===0 && number%3===0;

  console.log('48 is divisible by 6.');
  console.log('48 is not divisible by 6.');


48 is divisible by 6.

3. Both operands evaluate to a truthy or falsy value.

In JavaScript, the following are considered falsy values:

  • null
  • undefined
  • NaN
  • 0
  • -0
  • "" (empty string)

These six values work as false value.

Apart from the falsy values, all other values are truthy values. For example, objects, arrays, etc.

Logical AND operator starts by evaluating the left operand. If the value of the left operand is falsy. In that case, it returns that falsy value and does not evaluate the right operand. On the other hand, if the value of the left operand is truthy, then logical AND operator evaluates the right operand and returns the value of the right operand. This behavior of logical AND operator is used in the following scenarios:

If you want to execute a code when the condition is true, then instead of using the if statement, use the following code:

let a = 10,
    b = 10;

function show(){
  console.log("Both are equal.");

if(a === b){ //Call show() only if a is equal to b
(a === b) && show(); //This code will do the same thing.


Both are equal.
Both are equal.

Recommended Posts