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 (&&=
) 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
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:
const x = 0;
x &&= 2;
Auch das folgende würde den Setter nicht auslösen:
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.
const x = 0;
x &&= console.log("y evaluated");
// Logs nothing
Beispiele
Verwendung der logischen UND Zuweisung
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 |