BuildBot

JavaScript, Refreshed

Modern syntax & immutability

Lesson 5 of 5

What you'll learn

  • Safely read deep values with ?. and supply defaults with ??
  • Know why const prevents reassignment but not mutation
  • Update objects immutably by returning new copies

Two operators clean up a huge amount of defensive code. Optional chaining (?.) short-circuits to undefined if a link in the chain is null or undefined, instead of throwing. Nullish coalescing (??) supplies a fallback only when the left side is null or undefined — unlike ||, it won't swallow valid falsy values like 0 or "".

const user = { profile: null };
user.profile?.name;        // undefined, no crash
user.profile?.name ?? "Anonymous"; // "Anonymous"

const count = 0;
count || 10;  // 10  — wrong, 0 is valid
count ?? 10;  // 0   — right, only null/undefined fall back

const locks the binding, not the value

const prevents reassignment of the variable, but if it holds an object you can still mutate that object's contents. The binding is constant; the data isn't.

const config = { theme: "dark" };
config.theme = "light"; // allowed — mutating the object
// config = {};         // TypeError — reassigning the binding

Immutable updates

Rather than mutating shared state, prefer returning a new object with the change applied — spread the old one, then override the fields you want. This keeps the original intact, which is exactly what frameworks like React rely on to detect change.

Shallow copies are shallow

{ ...obj } copies the top level only. Nested objects are still shared by reference — spread each level you intend to change, or the "copy" will mutate the original underneath you.

The challenge applies an immutable update: it returns a fresh object with one field changed and proves the original is untouched.

Immutable update

Run it. updateField returns a new object; the original keeps its old value and stays a different reference.

Loading editor…

That's the refresher — values, functions, data, async, and modern syntax, each with a model you can run.

Sign in to save your progress across devices.