Result Types and Either Pattern
You'll learn: A functional programming approach to handle errors by returning success/failure objects instead of throwing exceptions.
The Core Idea
Instead of throwing errors that interrupt your program flow, you can return an object that describes what happened — either success with a value, or failure with an error. This is called a Result type or Either pattern.
Think of it like a package delivery: instead of the delivery person throwing your package at your door (or throwing an error), they hand you a box that's labeled as either "Success: Package inside" or "Failure: Here's why it didn't arrive." You open the box and handle each case explicitly.
Basic Result Type
function divide(a, b) {
if (b === 0) {
return { ok: false, error: "Cannot divide 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);
}
The Either Pattern
The Either pattern names the two possibilities: Left (traditionally for errors) and Right (for success values).
function parseNumber(str) {
const num = Number(str);
if (isNaN(num)) {
return { type: "left", error: "Not a valid number" };
}
return { type: "right", value: num };
}
const result = parseNumber("42");
if (result.type === "right") {
console.log("Parsed:", result.value);
} else {
console.log("Failed:", result.error);
}
Why This Matters
No surprises or uncaught exceptions. Every caller knows errors are possible because the return type says so. You handle success and failure explicitly, making your code more predictable and easier to reason about.
Key Takeaway: Result types and the Either pattern offer a functional alternative to throwing errors — return objects that explicitly represent success or failure, forcing callers to handle both paths.