O'Reilly logo

Eloquent JavaScript by Marijn Haverbeke

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

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

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required