Dealing with missing values with Maybe

A common problem in programming is dealing with missing values. There are many possible causes for this situation: a web service Ajax call may have returned an empty result, a dataset could be empty, an optional attribute might be missing from an object, and so on. Dealing with this kind of situation, in a normal imperative fashion, requires adding if statements or ternary operators everywhere to catch the possible missing value in order to avoid a certain runtime error. We can do a bit better by implementing a Maybe functor to represent a value that may (or may not) be present! We will use two classes, Just (as in just some value) and Nothing, both of which are functors themselves. The Nothing functor ...

Get Mastering JavaScript Functional Programming - Second Edition now with O’Reilly online learning.

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