Modern JavaScript and Error Handling

The ES2015+ features you will see in every codebase, plus throwing, catching and reporting errors properly.

Intermediate · about 5 hours · difficulty 2/5

Learn first: Objects, this and Prototypes

Since 2015, JavaScript gets a new edition every year. Most modern code, and every framework's documentation, assumes you know these features.

Features you will use daily

  • Destructuring of objects and arrays, with defaults and renaming.
  • Spread and rest (...) for copying, merging and variadic functions.
  • Template literals for interpolation and multiline strings.
  • Optional chaining a?.b?.() and nullish coalescing ??.
  • Shorthand properties, computed keys, default parameters.
  • Map and Set for keyed collections and uniqueness; WeakMap for caches tied to object lifetime.
  • Iterators and generators (function*), which power for...of.
  • Newer additions: Array.prototype.at(), toSorted()/toReversed() (non-mutating), Object.groupBy(), structuredClone().

Error handling

  • throw new Error("message") with a useful message; subclass Error for domain errors (class ValidationError extends Error).
  • try...catch...finally handles synchronous code and awaited promises. The cause option (new Error("Save failed", { cause: err })) preserves the original error.
  • Unhandled promise rejections do not crash the page but are easy to miss; listen for unhandledrejection and error on window to report them.
  • Do not swallow errors with an empty catch. Either handle it (show UI, retry) or rethrow.

Pitfall

Catching too broadly hides bugs. Catch where you can do something meaningful, typically at a UI boundary that shows the user a message.

Move on when you can read unfamiliar modern code without pausing on syntax and your async code never fails silently.

Key concepts

  • Destructuring
  • Spread and rest
  • Optional chaining and nullish coalescing
  • Map, Set and WeakMap
  • Iterators and generators
  • Non-mutating array methods: toSorted, toReversed, with
  • try, catch, finally
  • Custom errors and error cause
  • Global error and unhandledrejection events

Mini project

Refactor an old-style ES5 script (var, concatenation, manual loops) into modern syntax, add a custom ValidationError, and add a global error listener that shows a friendly banner.

Check yourself

Why is const { user: { name } = {} } = response safer than response.user.name?

Free resources