Apps Artificial Intelligence CSS DevOps Go JavaScript Laravel Linux MongoDB MySQL PHP Python Rust Svelte Vue

JavaScript `||=`: Logical OR Assignment

1 min read .
JavaScript `||=`: Logical OR Assignment

The logical OR assignment operator, ||=, assigns a new value only when the current left-hand value is falsy.

let name = '';
name ||= 'Guest';
console.log(name); // 'Guest'

Falsy values include false, 0, -0, 0n, '', null, undefined, and NaN.

Defaults in Functions

function greet(user) {
  user ||= 'Stranger';
  console.log(`Hello, ${user}!`);
}

greet('Alice'); // Hello, Alice!
greet();        // Hello, Stranger!

For ordinary function parameters, a default parameter is often clearer:

function greet(user = 'Stranger') {
  console.log(`Hello, ${user}!`);
}

Object Properties

const settings = { theme: '', fontSize: 14 };
settings.theme ||= 'light';

||= vs. ??=

Use ||= when every falsy value should trigger the default. Use ??= when only null or undefined means “missing”:

let count = 0;
count ||= 10; // 10

let total = 0;
total ??= 10; // remains 0

That distinction is important for valid values such as 0, false, and the empty string.

Conclusion

||= is concise for assigning a fallback when the existing value is falsy. When zero, false, or empty strings are valid data, prefer ??= so those values are preserved.

Related Posts

chevron-up