JavaScript Exceptions versus Explicit Result Objects
Quick answer
Expected invalid input can be represented as an ordinary result object, while exceptions transfer control away from the current path. Both are useful when their contracts are explicit.
How it works
A discriminated result such as {ok: true, value: 4} or {ok: false, error: "invalid"} lets callers branch on ok. An exception-based API instead returns a successful value or throws. Choose one clear convention for a given operation; result objects are ordinary objects, not a special language type. Unexpected programming faults need not be converted into routine invalid-input results.
function read(n) { return n >= 0 ? {ok:true, value:n} : {ok:false, error:"negative"}; }const result = read(0);console.log(result.ok, result.value);Expected output in Node.js:
true 0Zero is a successful value because success is explicit.
function read(n) { if (n < 0) return {ok:false, error:"negative"}; return {ok:true, value:n}; }const result = read(-2);console.log(result.ok, result.error);Expected output in Node.js:
false negativeThe invalid value is returned as ordinary data, not thrown.
Common mistakes
Never test success with if (result.value) when zero is valid. Check the discriminator.
Practice
Implement an explicit success/failure result for a bounded nonnegative count and check zero separately.
Check Your Understanding
Solidify your learning with the interactive assessment directly below this lesson.
Concept Quiz & Questions
JavaScript Exceptions versus Explicit Result Objects — Knowledge Check
Apply the taught concept and predict the output.
Which field should determine success in the shown result-object convention?
Does returning {ok:false} automatically transfer control to catch?
When can result objects be particularly useful?
What is the exact console output in JavaScript Exceptions versus Explicit Result Objects example 1?
function read(n) { return n >= 0 ? {ok:true, value:n} : {ok:false, error:"negative"}; }const result = read(0);console.log(result.ok, result.value);What is the exact console output in JavaScript Exceptions versus Explicit Result Objects example 2?
function read(n) { if (n < 0) return {ok:false, error:"negative"}; return {ok:true, value:n}; }const result = read(-2);console.log(result.ok, result.error);