liveBook · Manning

Option

As explained in Functional Programming in JavaScript

A monadic type that represents an optional value, distinguishing presence from absence without using null directly.

Option represents either a present value or no value, replacing scattered null checks with a composable container. Its concrete cases are Just(value) and Nothing(). section 5.3

Safely reading a nested value

Instead of checking student, school, and address one by one, map each lookup through an option and provide a fallback: student.map(prop('school')).map(prop('address')).map(prop('country')).getOrElse('Country does not exist!'). section 5.3

Option supports a small set of practical behaviors:

  • Maps functions over Just values while leaving Nothing unchanged. section 5.3
  • Converts nullable results with fromNullable and supplies defaults with getOrElse. section 5.3
  • Keeps absence from throwing until code explicitly attempts to extract a missing value. section 5.3
// safeFindObject :: DB -> String -> Maybe
const safeFindObject = R.curry((db, id) => {
   return Maybe.fromNullable(find(db, id));
});
// safeFindStudent :: String -> Maybe(Student)
const safeFindStudent = safeFindObject(DB('student'));

const address = safeFindStudent('444-44-4444').map(R.prop('address'));
address; //-> Just(Address(...)) or Nothing

Follow a database lookup that returns Just(address) or Nothing, then maps a property safely. section 5.3

How Functional Programming in JavaScript covers it

How deep it goes
Defines Just and Nothing, demonstrates mapping and defaults, and stops short of detailing the complete monad API.
Examples
Uses nullable student lookups, nested school addresses, DOM-style defaults, and database records wrapped as Just or Nothing.
What it assumes
Assumes basic JavaScript functions and nullable values while teaching monadic wrapping through concrete examples.
What you can do after
Apply it via mapping and getOrElse to compose nullable lookups and provide explicit fallback values.
How it connects
Connects option to monads, functors, nullability, composition, and Either.

Also explained in

Compare how 9 books explain option →

Related concepts

This explainer was generated by Manning's knowledge graph from the text of Functional Programming in JavaScript. The section links point to the parts of the book it draws on.