Patterns as words

Lesson 7 Guards and defaults

6 min read · JavaScript · Quiz

early return, optional access and the default-value traps

What you'll learn

  • Read a guard clause and say what it protects
  • Tell a real missing value from a falsy one
  • Spot the default-value traps AI code falls into

AI code is full of defaults and guards. Most are fine. A few quietly turn a real value into the wrong one.

The idea

A guard checks a condition up front and leaves early, so the rest of the function can assume the good case. Read a guard as a promise: after this line, this is true.

A default supplies a value when one is missing. The trap is what counts as missing. In JavaScript, || replaces every falsy value (0, "", false), while ?? replaces only null and undefined. And ?. stops at a missing value and gives undefined instead of an error.

describe.js
1function describe(options) {2  if (!options) return "defaults";3  const size = options.size || 20;4  const owner = options.user?.name ?? "guest";5  return `${owner}: ${size}`;6}
  1. Line 2 A guard. After it, options is not undefined or null. (An empty object {} is truthy in JavaScript and gets past.)
  2. Line 3 || replaces 0 and "" too. If size: 0 can be a real value, this line is a bug.
  3. Line 4 ?. and ?? react only to a missing value, so a name of "" would stay "".

Take away

  • Read a guard as a promise about the lines after it.
  • Ask of every default: can 0, "" or false be a real value here?
  • || means "falsy"; ?? means "missing".

Quiz: test yourself

7 questions: a quick quiz, then a review drill. Pick an answer to see why it's right.