論理積代入 (&&=)

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真値である場合にのみ代入を行います。

試してみましょう

let a = 1;
let b = 0;

a &&= 2;
console.log(a);
// Expected output: 2

b &&= 2;
console.log(b);
// Expected output: 0

構文

js
expr1 &&= expr2;

解説

短絡評価 (ショートサーキット)

論理積演算子は左から右に評価され、次のルールを使って短絡評価の可能性があるかどうかテストされます。

(偽値の式) && expr は、偽値の式が短絡評価されます。

短絡評価とは、上記の expr 部分が評価されないことを意味します。したがって、評価された場合の副作用は発生しません (例えば、expr が関数呼び出しである場合、呼び出しは行われません)。

論理積代入も短絡評価されます。これは、x &&= y が以下と等価であることを意味します。

js
x && (x = y);

そして、常に代入が行われる以下とは等価ではありません。

js
x = x && y;

論理積代入演算子の使用

js
let x = 0;
let y = 1;

x &&= 0; // 0
x &&= 1; // 0
y &&= 1; // 1
y &&= 0; // 0

仕様書

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 AND assignment (x &&= y)

Legend

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

Full support
Full support

関連情報