You are previewing Eloquent JavaScript.

Eloquent JavaScript

Cover of Eloquent JavaScript by Marijn Haverbeke Published by No Starch Press

Handling Errors

Unexpected input, or some other problematic circumstance, often leads to functions not being able to do what they are supposed to do. Take, for example, this function, between, which extracts the part of a string between two substrings:

function between(string, start, end) {
  var startAt = string.indexOf(start) + start.length;
  var endAt = string.indexOf(end, startAt);
  return string.slice(startAt, endAt);

between("Louis 'Pops' Armstrong", "'", "'");
→ "Pops"

When start or end is not found in the input, what should this function do? It cannot return what it is supposed to return, because the question it was asked doesn’t make sense.

Returning a Special Value

When a function encounters a problem that it cannot solve itself, one possible ...

The best content for your career. Discover unlimited learning on demand for around $1/day.