Example 1 — Keep 0 with ??=
0 is not nullish.
JavaScript
let n = 0;
n ??= 10;
console.log(n);How It Works
- ??= does not replace 0.
Logical assignment operators update a variable only in certain cases: ||= when falsy, &&= when truthy, ??= when null or undefined.
let a = null;
a ??= "default";
console.log(a);
let b = 0;
b ||= 5;
console.log(b);0 is not nullish.
let n = 0;
n ??= 10;
console.log(n);Assign when left is truthy.
let x = { ok: true };
x &&= { ok: false };
console.log(x.ok);Same idea as expressions.
let v = null;
v = v ?? "x";
console.log(v);CODETOFUN NEWS
Get the latest IT news, programming updates, and technology trends directly on your phone.
Your daily dose of tech, straight to your feed.
6 people found this page helpful