Conditional Logic Patterns in JavaScript

JavaScript offers a versatile set of tools for handling conditional logic, beyond the traditional if-else statements and ternary operators.

Two powerful features that stand out for modern JavaScript development are the nullish coalescing operator (??) and logical assignment operators. These features provide elegant solutions for common coding scenarios, making code more readable and efficient.

Nullish Coalescing Operator (??)

The nullish coalescing operator (??) is a logical operator that returns its right-hand side operand when its left-hand side operand is null or undefined, and otherwise returns its left-hand side operand. This operator is particularly useful for assigning default values.

I. Syntax

let result = value ?? defaultValue;

II. Use Case: Setting Default Values

Before ??, setting default values often required the use of the logical OR operator (||). However, this could lead to unintended consequences if the left-hand value was considered falsy (0, '', false, etc.).

let input = 0;
let output = input || 10; // output would be 10, not 0

With nullish coalescing:

let input = 0;
let output = input ?? 10; // output is 0

This ensures that 0 or an empty string '' are not replaced by a default value, addressing a common pitfall of using || for default assignments.

Logical Assignment Operators

Logical assignment operators combine logical operations (&&, ||, ??) with assignment (=). These operators provide a concise way to write common patterns of conditional assignment.

I. Types of Logical Assignment Operators

  • Logical OR assignment (||=): Assigns the right-hand value if the left-hand value is falsy.
  • Logical AND assignment (&&=): Assigns the right-hand value if the left-hand value is truthy.
  • Logical nullish assignment (??=): Assigns the right-hand value if the left-hand value is null or undefined.

II. Use Cases

Filling in Default Values

let options = { timeout: 0 };
options.timeout ||= 5000; // Won't assign 5000 because 0 is falsy
options.timeout ??= 5000; // Correctly keeps timeout as 0

Conditional Property Assignment

let user = { name: 'Alice', age: null };

// Only update age if it's null or undefined
user.age ??= 30;
console.log(user.age); // 30

// Only update name if it already has a truthy value &&= 'Bob';
console.log(; // Bob

Real-world Applications

I. Handling API Responses

When working with API responses, you often encounter null or undefined values. The nullish coalescing operator helps safely access properties or provide default values.

function getUserDisplayName(user) {
  return user.displayName ?? 'Anonymous User';

II. Configuration Objects

For configuration objects where certain properties may not be provided, logical assignment operators can simplify setting defaults or modifying values based on conditions.

function configure(options) { ??= 'localhost';
  options.port ||= 3000;
  return options;