逻辑或赋值(||=)

Baseline Widely available

This feature is well established and works across many devices and browser versions. It’s been available across browsers since September 2020.

逻辑或赋值(x ||= y)运算仅在 x值时为其赋值。

尝试一下

const a = { duration: 50, title: "" };

a.duration ||= 10;
console.log(a.duration);
// Expected output: 50

a.title ||= "title is empty.";
console.log(a.title);
// Expected output: "title is empty."

语法

js
expr1 ||= expr2

描述

逻辑或的短路运算意味着 x ||= y 与下式等价:

js
x || (x = y);

如果左操作数不为假值,则由于逻辑或运算符的短路运算,不进行赋值操作。例如,由于 xconst(常量),以下式子不会抛出错误:

js
const x = 1;
x ||= 2;

也不会触发 setter 函数:

js
const x = {
  get value() {
    return 1;
  },
  set value(v) {
    console.log("调用了 setter");
  },
};

x.value ||= 2;

实际上,如果 x 为真值,则根本不会对 y 求值。

js
const x = 1;
x ||= console.log("y 进行了求值");
// 什么都不会输出

示例

设定默认内容

当“lyrics”元素为空时,则显示默认值:

js
document.getElementById("lyrics").textContent ||= "没有歌词。";

在这里,短路运算特别有用,因为元素不会产生不必要的更新,也不会引起诸如额外的解析、渲染、失去焦点等副作用。

注意:请注意检查 API 返回的值。如果返回的是空字符串(是值),则必须使用 ||=,以显示“没有歌词。”而不是空内容。然而,如果接口返回 nullundefined,则应该使用 ??=(空值合并赋值)运算符代替空白内容。

规范

Specification
ECMAScript® 2025 Language Specification
# sec-assignment-operators

浏览器兼容性

Report problems with this compatibility data on GitHub
desktopmobileserver
Chrome
Edge
Firefox
Opera
Safari
Chrome Android
Firefox for Android
Opera Android
Safari on iOS
Samsung Internet
WebView Android
WebView on iOS
Deno
Node.js
Logical OR assignment (x ||= y)

Legend

Tip: you can click/tap on a cell for more information.

Full support
Full support

参见