Logisches UND-Zuweisung (`&&=`)

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.

Der logische UND-Zuweisungsoperator (&&=) wertet nur den rechten Operanden aus und weist ihn dem linken zu, wenn der linke Operand truthy ist.

Probieren Sie es aus

let a = 1;
let b = 0;

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

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

Syntax

js
x &&= y

Beschreibung

Die logische UND-Zuweisung short-circuits, was bedeutet, dass x &&= y gleichwertig ist mit x && (x = y), außer dass der Ausdruck x nur einmal ausgewertet wird.

Es erfolgt keine Zuweisung, wenn die linke Seite nicht "truthy" ist, aufgrund des Short-Circuitings des logischen UND-Operators. Zum Beispiel führt der folgende Fall nicht zu einem Fehler, obwohl x als const deklariert ist:

js
const x = 0;
x &&= 2;

Ebenso würde der folgende Fall keinen Setter auslösen:

js
const x = {
  get value() {
    return 0;
  },
  set value(v) {
    console.log("Setter called");
  },
};

x.value &&= 2;

Tatsächlich wird y überhaupt nicht ausgewertet, wenn x nicht "truthy" ist.

js
const x = 0;
x &&= console.log("y evaluated");
// Logs nothing

Beispiele

Verwendung von logischer UND-Zuweisung

js
let x = 0;
let y = 1;

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

Spezifikationen

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

Browser-Kompatibilität

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

Siehe auch