Knowledge baseExam Center
ENEnglish
Choose language13

CKTIS / JavaScript

Logical OR assignment (||=)

The ||= operator assigns the right-hand value only when the target's current value is falsy. It short-circuits evaluation and evaluates the target reference only once.

Version: ECMAScript and Web APIs; exact feature edition and browser support reviewed per entry; Node 24 in repository does not prove browser API support

Syntax

target ||= expression

target ||= expression reads the target's value and tests it using ToBoolean. If it is truthy, the operator returns it without evaluating expression or assigning. Otherwise, it evaluates the right-hand side, assigns its value, and returns that value; the result need not be a boolean.

Falsy values include false, 0, -0, 0n, "", NaN, null, and undefined. Consequently, ||= can overwrite a valid zero or empty string. Use ??= when only null and undefined should mean a missing value. The |= operator performs bitwise OR and is not a substitute for ||=.

The target reference is evaluated only once. obj[key()] ||= value calls key() once, unlike the naive expansion obj[key()] = obj[key()] || value. A getter can run during the read, but the setter is skipped when the retrieved value is truthy. The target must be a valid assignment target; an undeclared variable cannot be initialized this way.

The operator is part of ECMAScript 2021. It is language syntax, not a Web API. For deployment, check syntax support in the target engines or transform the code; Node 24 in a repository does not establish browser support.

Examples

let calls = 0;
function fallback() {
  calls += 1;
  return "Guest";
}

const profile = { name: "", role: "admin" };
profile.name ||= fallback();
profile.role ||= fallback();

let limit = 0;
limit ||= 10;

console.log(profile.name);
console.log(profile.role);
console.log(calls);
console.log(limit);

Result

Guest
admin
1
10

The displayed code and declared result were verified in an isolated environment using the method recorded in the verification evidence for this exact version.

Sources