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.

We’d love to hear your thoughts on the next set of proposals for the JavaScript language. You can find a description of the proposals here.
Please take two minutes to fill out our short survey.

Der logische UND Zuweisungsoperator (&&=) bewertet nur den rechten Operanden und weist den linken nur dann 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-circuit, was bedeutet, dass x &&= y gleichwertig ist mit x && (x = y), außer dass der Ausdruck x nur einmal ausgewertet wird.

Keine Zuweisung erfolgt, wenn die linke Seite nicht truthy ist, aufgrund des Short-Circuiting des logischen UND Operators. Zum Beispiel, das folgende wirft keinen Fehler, obwohl x ein const ist:

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

Auch das folgende würde den Setter nicht auslösen:

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

x.value &&= 2;

Tatsächlich wird y nicht bewertet, wenn x nicht truthy ist.

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

Beispiele

Verwendung der logischen UND Zuweisung

js
let x = 0;
let y = 1;

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

Spezifikationen

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

Browser-Kompatibilität

Siehe auch