throwing Errors in JavaScript
throw launches any value up the stack to the nearest matching catch — but only Error objects (with message, name, and stack traces) debug sanely. throw "oops" works yet strands responders without stacks or types; throw new Error("oops") carries both.
Throw for programmer-facing contract violations (invalid arguments, impossible states); return error values or Results for expected failures (missing records, validation). Sync throws unwind immediately; async throws become rejections caught by await-try or .catch.
Throw Errors, not values
throw new Error("msg") — stacks, names, and instanceof checks versus bare strings' nothing.
Contracts throw, flows return
Violated preconditions and impossible states throw; expected absences (not found) return null/undefined or Results.
Sync unwinds now
throw exits all frames to the nearest try — code after it in the block never runs.
Async throw rejects
Throws inside async functions and .then callbacks become rejections — handled by await-try or terminal .catch.
function divide(a, b) { if (b === 0) throw new Error("divide by zero"); return a / b;}try { divide(1, 0);} catch (e) { console.log("caught:", e.message);}Recommended resourcesAffiliate links · may earn us a commission
Recommended for learners
Practice what you learned
Re-implement each visualized algorithm in JavaScript yourself — building beats watching.