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, or a dataset could be empty, or an optional attribute might be missing from an object, and so on. Dealing with this kind of situation, in normal imperative fashion, requires adding if statements or ternary operators everywhere, to catch the possible missing value, avoiding a certain runtime error. We can do a bit better by implementing a Maybe functor, to represent a value that may be (or may not be) present! We will use two classes, Just (as in just some value) and Nothing, one for each functor:

class Nothing extends Functor {

Get Mastering Javascript Functional Programming now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.