Course contentsShow
← JavaScript
Lesson 2437 of 2,72349. Common Patterns and IdiomsFree lesson

The Result Pattern: Explicit Success or Failure

Representing operations as { ok: true, value } or { ok: false, error } objects for explicit error handling.

The Result Pattern: Explicit Success or Failure

What you'll learn: How to represent operation outcomes as explicit success or failure objects instead of throwing exceptions.

The Core Idea

The Result Pattern replaces throwing errors with returning a data structure that explicitly indicates success or failure. Instead of letting functions crash or bubble exceptions, you return an object like { ok: true, value: result } for success or { ok: false, error: errorInfo } for failure.

This makes error handling mandatory and visible at the call site. The caller must check the ok flag before accessing the value or error, making failure paths explicit in your code flow.

Why Use This Pattern?

After learning about throw/try-catch limitations, you know that exceptions can be invisible in function signatures and easy to forget. The Result Pattern solves this by making every operation's potential failure part of its return type. You can't accidentally ignore an error — you must explicitly check ok first.

Think of it like a package delivery: instead of the delivery person throwing your package over the fence (exception) where you might miss it, they hand you a tracking receipt that says either "delivered successfully, here's your item" or "delivery failed, here's why."

Basic Structure

function divide(a, b) {
  if (b === 0) {
    return { ok: false, error: 'Division by zero' };
  }
  return { ok: true, value: a / b };
}

const result = divide(10, 2);
if (result.ok) {
  console.log('Result:', result.value); // 5
} else {
  console.log('Error:', result.error);
}

Notice: no try-catch blocks needed, and the error path is visible right in the control flow.

Key Takeaway: The Result Pattern uses { ok: true, value } or { ok: false, error } objects to make success and failure explicit, forcing callers to handle both cases consciously rather than risking unhandled exceptions.