30 min·advanced

Lesson 2

Errors & defensive code

Build a practical mental model for errors & defensive code and use it in working JavaScript.

By the end, you will be able to…

  • Explain errors & defensive code in your own words
  • Use errors & defensive code in a small program
  • Recognize and debug a common failure mode

Build the mental model

Defensive code validates its assumptions about input before acting on them, returning a sensible fallback instead of crashing when those assumptions are violated by unexpected data.

Syntax and working example

Read the code from inputs to output. Predict what it prints, then run it and change one value.

Working example
Expected output: Never throws, even for null or malformed input

Why this matters

Real input — API responses, user forms — is messier than the happy path you tested; defensive checks are what keep a feature working in production.

Real-world example

A profile page that shows 'Unknown user' instead of crashing when a malformed record comes back from an API is defensive code in action.

Common mistakes

  • Assuming input always matches the expected shape
  • Validating only in development and skipping it in the code that ships
  • Throwing generic errors with no useful message for whoever debugs it later

Try it yourself

Challenge

Make getFirstName defensive against a missing or malformed user argument.

Practice

Knowledge check

What is 'defensive code' primarily protecting against?

Summary

Validate assumptions about input explicitly and fail gracefully with fallbacks instead of crashing.