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 ...

Get Eloquent JavaScript now with O’Reilly online learning.

O’Reilly members experience live online training, plus books, videos, and digital content from 200+ publishers.