Using multiple logical "or" operators

Learn using multiple logical "or" operators with practical examples, diagrams, and best practices. Covers javascript, logic, control-flow development techniques with visual explanations.

Mastering Multiple Logical 'OR' Operators in JavaScript

Hero image for Using multiple logical "or" operators

Explore the nuances of using multiple logical 'OR' (||) operators in JavaScript for concise and effective conditional logic, default value assignments, and short-circuit evaluation.

The logical OR operator (||) is a fundamental part of JavaScript, allowing you to combine multiple conditions. While its basic use is straightforward, understanding how it behaves with multiple operands, especially concerning truthiness and short-circuit evaluation, is crucial for writing clean, efficient, and bug-free code. This article delves into the various applications and behaviors of multiple || operators.

Understanding Logical OR (||) Basics

At its core, the || operator evaluates operands from left to right. It returns the value of the first operand that evaluates to true (or a 'truthy' value). If all operands evaluate to false (or 'falsy' values), it returns the value of the last operand. This behavior is known as 'short-circuit evaluation' and is key to its power.

const a = true;
const b = false;
const c = 'hello';
const d = 0;

console.log(a || b); // true (a is truthy)
console.log(b || a); // true (b is falsy, then a is truthy)
console.log(d || c); // 'hello' (d is falsy, then c is truthy)
console.log(b || d); // 0 (both are falsy, returns the last one)

Basic examples of the logical OR operator

Multiple OR Operators for Conditional Logic

When you chain multiple || operators, the short-circuit evaluation continues across all operands. The expression will return the first truthy value it encounters. If no truthy value is found, it will return the last falsy value. This is incredibly useful for checking if any of several conditions are met.

flowchart LR
    start[Start] --> A{Condition 1?}
    A -- Yes --> resultA[Return Value of Condition 1]
    A -- No --> B{Condition 2?}
    B -- Yes --> resultB[Return Value of Condition 2]
    B -- No --> C{Condition 3?}
    C -- Yes --> resultC[Return Value of Condition 3]
    C -- No --> resultD[Return Value of Condition 3 (last operand)]

Flowchart illustrating short-circuit evaluation with multiple OR operators

function checkAccess(role, status, subscription) {
  return role === 'admin' || status === 'active' || subscription === 'premium';
}

console.log(checkAccess('guest', 'inactive', 'basic')); // false
console.log(checkAccess('admin', 'inactive', 'basic')); // true (role is 'admin')
console.log(checkAccess('guest', 'active', 'basic'));   // true (status is 'active')
console.log(checkAccess('guest', 'inactive', 'premium')); // true (subscription is 'premium')

Using multiple OR for checking multiple access conditions

Assigning Default Values with Multiple OR

One of the most common and powerful uses of multiple || operators is to assign a default value to a variable if the primary value is null, undefined, or any other falsy value. This provides a concise alternative to more verbose if/else statements or ternary operators.

function getUserSettings(settings) {
  const theme = settings.theme || 'dark';
  const fontSize = settings.fontSize || 16;
  const language = settings.language || 'en-US';
  const username = settings.username || 'Guest User';

  console.log(`Theme: ${theme}, Font Size: ${fontSize}, Language: ${language}, User: ${username}`);
}

getUserSettings({ theme: 'light', fontSize: 14 }); // Theme: light, Font Size: 14, Language: en-US, User: Guest User
getUserSettings({}); // Theme: dark, Font Size: 16, Language: en-US, User: Guest User
getUserSettings({ username: 'Alice' }); // Theme: dark, Font Size: 16, Language: en-US, User: Alice

Assigning default values using the logical OR operator

Chaining Fallback Options

Multiple || operators can be chained to provide a series of fallback options. This is particularly useful when you need to try several sources for a value, using the first available truthy one.

const userDisplayName = user.preferredName || user.fullName || user.username || 'Anonymous';

console.log(userDisplayName); // Will output the first truthy value found

// Example scenarios:
const user1 = { preferredName: 'John Doe', fullName: 'Jonathan Doe', username: 'jdoe' };
const user2 = { fullName: 'Jane Smith', username: 'jsmith' };
const user3 = { username: 'bob_the_builder' };
const user4 = {};

console.log(user1.preferredName || user1.fullName || user1.username || 'Anonymous'); // John Doe
console.log(user2.preferredName || user2.fullName || user2.username || 'Anonymous'); // Jane Smith
console.log(user3.preferredName || user3.fullName || user3.username || 'Anonymous'); // bob_the_builder
console.log(user4.preferredName || user4.fullName || user4.username || 'Anonymous'); // Anonymous

Chaining fallback options for a user's display name