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

Implementing a Result Type in JavaScript

Creating simple Result.ok() and Result.err() factory functions to standardize success and failure values.

Implementing a Result Type in JavaScript

You'll learn how to build a simple Result type with factory functions that wrap success and failure values in a uniform interface.


The Core Idea

Instead of throwing errors or mixing return types (null, -1, error strings), we create a container object that explicitly represents either success or failure. Two factory functions make this easy:

  • Result.ok(value) — wraps a successful result
  • Result.err(error) — wraps an error/failure

Both return objects with the same structure, so calling code can handle them uniformly without try-catch.


Basic Implementation

class Result {
  constructor(isOk, value) {
    this.isOk = isOk;
    this.value = value;
  }

  static ok(value) {
    return new Result(true, value);
  }

  static err(error) {
    return new Result(false, error);
  }
}

// Usage:
function divide(a, b) {
  if (b === 0) {
    return Result.err('Division by zero');
  }
  return Result.ok(a / b);
}

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

const failure = divide(10, 0);
if (!failure.isOk) {
  console.log('Error:', failure.value); // 'Division by zero'
}

The isOk boolean flag tells you which kind of result you have. The value property holds either the success data or the error information.


Why This Matters

Every function returns a Result object. No surprises, no exceptions—just a predictable container you can inspect. This makes error handling visible and explicit in your code flow.

Key Takeaway:
Result.ok() and Result.err() factory functions standardize success and failure into a single, inspectable type—making errors first-class values instead of exceptional control flow.