JavaScript Basics

JavaScript Advanced

JavaScript Arrays

JavaScript Functions

JavaScript Objects

JavaScript DOM

JavaScript String

How to use Logical OR (||) operator in JavaScript?

Logical OR operator is represented by the double pipe (||). It is a binary operator and expects two operands.

let result = operand1 || operand2;

Logical OR operator works in three ways:

1. Both operands are boolean values.

Logical OR returns true if one or both operands is true. If both operands are false, it returns false.

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

console.log(x || y); //true

2. Both operands are relational expressions.

Logical OR returns true if one or both operands evaluates to true. If both operands evaluate to false, it returns false.

let year = 2020;
let leapYear = year%4===0 || year%400===0;

if(leapYear){
  console.log('2020 is a leap year.');
}else{
  console.log('2020 is not a leap year.');
}

Output

2020 is a leap year.

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 OR operator starts by evaluating the left operand. Suppose the value of the left operand is truthy. In that case, it returns that truthy value and does not evaluate the right operand. On the other hand, if the value of the left operand is falsy, then logical OR operator evaluates the right operand and returns the value of that operand.

This behavior of logical OR operator is used in two scenarios:

a) Prior to ES6 default parameter, logical OR operator is used to set the default value for function parameters.

function add(a, b, c){
  a = a || 0;
  b = b || 0;
  c = c || 0;
  console.log(a); //1
  console.log(b); //2
  console.log(c); //0
  return a + b + c;
}

console.log(add(1, 2)); //3

In this example, the value for parameter c is not passed to the add() function. So, using logical OR operator, the default value of the parameter c is set to 0.

Note: To learn more about ES6 default parameter, visit How to use Default Parameters in JavaScript Function?

b) To set the first truthy value in a set of options.

You will find this concept in setting the Express server's port address.

let express = require('express');
let app = express();

app.get('/', function (req, res) {
  res.send('Hello World!');
});

let port = process.env.PORT || 3000;

app.listen(port);

The code process.env.PORT || 3000 will use the preconfigured port. If it is not set, then it will use port 3000.

Recommended Posts