JavaScript Double Pipe

Shraddha Paghdar Oct 12, 2023
JavaScript Double Pipe

Sometimes we are unaware whether a property of an object will contain a value or not, or a variable has been set or not. We want our code to work with a backup value even if the value is not set. This article will introduce JavaScript double pipe ||.

JavaScript supports various operators like assignment, arithmetic, logical, conditional, etc. JavaScript logical operators have typically been used with boolean (logical) values. If boolean values are used, they return a boolean value based on the type of operator.

The AND and OR operators return the value of one of the specified operands based on the result. So, when used with non-Boolean values, these operators can return a non-Boolean value. Logical operators support Logical AND (&&), Logical OR (||), and Logical NOT (!).

JavaScript Double Pipe

Logical OR returns expr1 if it can be converted to true; otherwise, it returns expr2. Therefore, if used with Boolean values, it will return True if the operand is true;; if both are false, false is returned.

Values that will be treated as false are null, NaN, 0, empty string ("" or ''), and undefined. Logical OR operator can be converted to Logical AND using !(!bCondition1 && !bCondition2). For more information, read the documentation of the Logical OR operator.

Syntax:

expr1 || expr2

Example Code:

let a = 'Hello';
let b;
console.log(a || 'Not Found');
console.log(a ? a : 'Not Found');
console.log(b || 'Not Found');

In the above example, the || checks if a evaluates to true. If it does, it will return Hello; otherwise, it returns Not Found. The same goes for b also.

The above expression can also be written using the ternary operator of JavaScript, which does the same thing. But logical or works as shorthand of JavaScript ternary operator. The output of the previous code is the same as shown below.

Output:

"Hello"
"Not Found"
Shraddha Paghdar avatar Shraddha Paghdar avatar

Shraddha is a JavaScript nerd that utilises it for everything from experimenting to assisting individuals and businesses with day-to-day operations and business growth. She is a writer, chef, and computer programmer. As a senior MEAN/MERN stack developer and project manager with more than 4 years of experience in this sector, she now handles multiple projects. She has been producing technical writing for at least a year and a half. She enjoys coming up with fresh, innovative ideas.

LinkedIn