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;
WeakMapfor caches tied to object lifetime. - Iterators and generators (
function*), which powerfor...of. - Newer additions:
Array.prototype.at(),toSorted()/toReversed()(non-mutating),Object.groupBy(),structuredClone().
Error handling
throw new Error("message")with a useful message; subclassErrorfor domain errors (class ValidationError extends Error).try...catch...finallyhandles synchronous code and awaited promises. Thecauseoption (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
unhandledrejectionanderroronwindowto 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
- The Modern JavaScript Tutorial (javascript.info)
- Error handling, try...catch (javascript.info)
- JavaScript reference (MDN)