typestar

Optional chaining and nullish in JavaScript

?. stops at null or undefined; ?? only falls back on those two.

const settings = { theme: { name: "dracula" }, limit: 0, label: "" };

console.log(settings.editor?.mode);
console.log(settings.theme?.name);
console.log(settings.missing?.deep?.value ?? "default");

console.log(settings.limit || 60);   // 60: zero is falsy
console.log(settings.limit ?? 60);   // 0: zero is not nullish
console.log(settings.label ?? "untitled");

const config = { retries: null };
config.retries ??= 3;
config.limit ??= 30;
console.log(config);

const maybeFn = settings.onSave;
console.log(maybeFn?.() ?? "no handler");

How it works

  1. a?.b is undefined instead of a TypeError.
  2. ?? differs from ||: zero and empty string are kept.
  3. ??= assigns only when the value is nullish.

Keywords and builtins used here

The run, in numbers

Lines
17
Characters to type
538
Tokens
145
Three-star pace
80 tpm

At the three-star pace of 80 tokens a minute, this run takes about 109 seconds.

Type this snippet

Step 4 of 5 in Bindings & values, step 4 of 43 in Language basics.

← Previous Next →