How does the || operator work in javascript?

javascript

As javascript is a loosely-typed language, we can perform logical operations on any type.

1 || 2; 
null || undefined;
"hello" || true;

All the above operations are valid in javascript.

First, javascript decides whether an operand is truthy or falsy and, then it performs the logical operations on them.

A simple way to determine whether a value is truthy or falsy is by evaluating them in a boolean context.

if(value) { ... };
Boolean(value);

Syntax

Operand_1 || Operand_2 || Operand_3

Return Value

Starting from left, it returns the first operand that is truthy. If no operand evaluates to a truthy value, it returns the last operand.

false || true || false;
// true

Let's consider the above example. The first truthy value we encounter is the second operand (true). Thus, the expression returns true.

{} || 0 || [];
// {} 

{} and [] are truthy values in javascript. So, the above expression returns the first operand({}).

Share and support us

Share on social media and help us reach more people