JavaScript and TypeScript course ยท Module 12: Functional Programming

FP Patterns: Functors and Monads

7 min read ยท
In this lesson4

Finding a dinosaur's zone takes three steps: find the dinosaur, take its zoneId, find the zone. Each step can return undefined, and one missed check ends in the middle of the night shift with TypeError: Cannot read properties of undefined. Code full of ifs protects against that, but it hides what we are actually doing.

In the advanced laboratory of Jurassic Park, we don't always know whether a DNA sample exists, whether the analysis succeeded, or whether the data is complete. Instead of checking conditions at every step (if/else), we can use elegant patterns from functional programming - functors and monads. They are like intelligent sample containers that know how to handle missing or damaged data on their own.

Functors - Containers with Mapping

A functor is an object (container) that implements a map method. It allows applying transformations to the value inside the container without having to extract it. You already know one functor: the array, whose map transforms the contents and returns a new array. The simplest functor of your own is a box for a single value:

// The simplest functor - Box (container)
class Box {
  constructor(value) {
    this.value = value;
  }

  map(fn) {
    return new Box(fn(this.value));
  }

  toString() {
    return 'Box(' + this.value + ')';
  }
}

map does not change this.value, it only creates a new Box with the result of the function - the same immutability principle you know from the previous lesson. Because every map returns a box, the calls chain together:

// Usage - chain of transformations
const result = new Box(8000)
  .map((weight) => weight / 1000)      // Box(8)
  .map((tons) => tons + ' tons')        // Box('8 tons')
  .map((label) => 'Weight: ' + label);  // Box('Weight: 8 tons')

console.log(result.value); // 'Weight: 8 tons'

Each step receives the unwrapped value, and the result goes back into the box. Only at the very end do we reach for result.value.

Maybe - Handling Missing Values

The Maybe monad solves the problem of null/undefined values. Instead of checking if (x !== null) everywhere, we wrap the value in a Maybe and let the monad handle missing data. The static method of creates the container, isNothing checks whether it is empty, map works as in Box but skips an empty container, flatMap takes a function that returns another Maybe, and getOrElse extracts the value or returns a default:

class Maybe {
  constructor(value) {
    this.value = value;
  }

  static of(value) {
    return new Maybe(value);
  }

  isNothing() {
    return this.value === null || this.value === undefined;
  }

  map(fn) {
    return this.isNothing() ? this : Maybe.of(fn(this.value));
  }

  flatMap(fn) {
    return this.isNothing() ? this : fn(this.value);
  }

  getOrElse(defaultValue) {
    return this.isNothing() ? defaultValue : this.value;
  }
}

All the safety sits in a single condition: an empty Maybe answers every map with itself, so the function never receives undefined. Now compare the zone lookup without Maybe and with it:

// Without Maybe - full of ifs
function getDinoZoneOld(park, dinoId) {
  const dino = park.dinosaurs.find((d) => d.id === dinoId);
  if (!dino) return 'Unknown';
  const zone = park.zones.find((z) => z.id === dino.zoneId);
  if (!zone) return 'Unknown';
  return zone.name;
}

// With Maybe - elegant chain
function getDinoZone(park, dinoId) {
  return Maybe.of(park.dinosaurs.find((d) => d.id === dinoId))
    .map((dino) => dino.zoneId)
    .flatMap((zoneId) => Maybe.of(park.zones.find((z) => z.id === zoneId)))
    .map((zone) => zone.name)
    .getOrElse('Unknown');
}

The ifs are gone, and the "not found" case is handled by a single getOrElse at the end. For the zone we use flatMap, because the function in that step returns a Maybe itself - a plain map would give a Maybe inside a Maybe. The order is always the same: wrap with Maybe.of, transform with map, join steps that return a Maybe with flatMap, and extract the result with getOrElse. The shortest chain is Maybe.of(data).map((d) => d.name).getOrElse('Unknown').

You know the same pair from arrays. flatMap maps first and then flattens the result by one level:

const zoneIds = ['A', 'B'];
const dinosByZone = { A: ['Rex', 'Blue'], B: ['Brachio'] };

zoneIds.map((id) => dinosByZone[id]);     // [['Rex', 'Blue'], ['Brachio']]
zoneIds.flatMap((id) => dinosByZone[id]); // ['Rex', 'Blue', 'Brachio']

map returns an array of arrays, and flatMap a single flat list. Maybe.flatMap does the same with boxes. For simply reading fields, the built-in dino?.zone ?? 'Unknown' is enough, and Maybe pays off when the steps are whole lookups.

Either - Error Handling

Maybe only says that a value is missing, not why. Either represents a value that can be a success (Right) or a failure (Left). It's a functional alternative to try/catch:

class Left {
  constructor(value) { this.value = value; }
  map(fn) { return this; }           // Ignores transformations
  flatMap(fn) { return this; }
  getOrElse(defaultValue) { return defaultValue; }
  isLeft() { return true; }
  isRight() { return false; }
}

class Right {
  constructor(value) { this.value = value; }
  map(fn) { return new Right(fn(this.value)); }
  flatMap(fn) { return fn(this.value); }
  getOrElse(defaultValue) { return this.value; }
  isLeft() { return false; }
  isRight() { return true; }
}

Both classes have the same API, but Right.map applies the function, while Left.map skips it and carries the error on. After the first failure, the rest of the chain does not run. Let's see this in sample validation:

// Usage in DNA sample validation
function validateSample(sample) {
  if (!sample.id) return new Left('Missing sample ID');
  if (sample.purity < 0.5) return new Left('Purity too low: ' + sample.purity);
  if (!sample.species) return new Left('Unknown species');
  return new Right(sample);
}

function processSample(sample) {
  return validateSample(sample)
    .map((s) => ({ ...s, processed: true }))
    .map((s) => ({ ...s, label: s.species + '-' + s.id }));
}

// Success
const good = processSample({ id: 'S001', purity: 0.95, species: 'T-Rex' });
good.getOrElse('Error'); // { id: 'S001', purity: 0.95, species: 'T-Rex', processed: true, label: 'T-Rex-S001' }

// Failure
const bad = processSample({ id: 'S002', purity: 0.3, species: 'Raptor' });
bad.getOrElse('Error'); // 'Error' (error: 'Purity too low: 0.3')

Sample S001 goes through both transformations. For S002 both map calls are skipped, but the message is not lost: it sits in bad.value, and bad.isLeft() returns true. Either does not catch exceptions on its own, though, so keep try/catch at the boundary with code that throws, such as JSON.parse.

How It All Fits Together

In FP jargon, a monad is a functor that also has flatMap (often called chain in libraries) and a way of putting a value into the container, such as of. The pillars of this module build up from the ground: pure functions, immutability, higher-order functions, composition with currying, and functors and monads at the top. You refactor imperative code in the same order: you find the side effects, extract pure functions, replace loops with map, filter and reduce, connect the steps with pipe, and wrap the risky places in Maybe or Either. A data pipeline has similar layers: parsing, validation with Maybe or Either, transformation with map, aggregation with reduce and a report - you will build one in the final project. Do not wrap everything in containers, though: they pay off at the boundary with data from the outside.

A functor, and the monad built on top of it, is simply a container that already knows what to do when the sample inside is missing or contaminated, which is how Maybe and Either carry a whole chain of transformations through to the end instead of scattering your code with null checks and try/catch blocks.

Code for this lesson: index.js
// FP patterns: functors and monads
console.log("=== Jurassic Park - Smart DNA Containers ===\n");

// --- EXAMPLE 1: The Box functor ---
console.log("--- Box functor ---");

class Box {
  constructor(value) { this.value = value; }
  map(fn) { return new Box(fn(this.value)); }
  toString() { return "Box(" + JSON.stringify(this.value) + ")"; }
}

const result = new Box(8000)
  .map((w) => w / 1000)
  .map((t) => t + " tons")
  .map((l) => "Weight: " + l);

console.log(result.toString()); // Box("Weight: 8 tons")

// --- EXAMPLE 2: Maybe ---
console.log("\n--- The Maybe monad ---");

class Maybe {
  constructor(value) { this.value = value; }
  static of(v) { return new Maybe(v); }
  isNothing() { return this.value === null || this.value === undefined; }
  map(fn) { return this.isNothing() ? this : Maybe.of(fn(this.value)); }
  flatMap(fn) { return this.isNothing() ? this : fn(this.value); }
  getOrElse(def) { return this.isNothing() ? def : this.value; }
  toString() { return this.isNothing() ? "Maybe(Nothing)" : "Maybe(" + JSON.stringify(this.value) + ")"; }
}

const park = {
  dinosaurs: [
    { id: "D01", name: "Rex", zoneId: "Z01" },
    { id: "D02", name: "Blue", zoneId: "Z02" },
  ],
  zones: [
    { id: "Z01", name: "Zone A" },
    { id: "Z02", name: "Zone B" },
  ],
};

function getDinoZone(parkData, dinoId) {
  return Maybe.of(parkData.dinosaurs.find((d) => d.id === dinoId))
    .map((dino) => dino.zoneId)
    .flatMap((zoneId) => Maybe.of(parkData.zones.find((z) => z.id === zoneId)))
    .map((zone) => zone.name)
    .getOrElse("Unknown");
}

console.log("Rex zone:", getDinoZone(park, "D01"));    // Zone A
console.log("Blue zone:", getDinoZone(park, "D02"));   // Zone B
console.log("Unknown:", getDinoZone(park, "D99"));     // Unknown

// --- EXAMPLE 3: Either ---
console.log("\n--- The Either monad ---");

class Left {
  constructor(value) { this.value = value; }
  map(fn) { return this; }
  flatMap(fn) { return this; }
  getOrElse(def) { return def; }
  isLeft() { return true; }
  isRight() { return false; }
  toString() { return "Left(" + this.value + ")"; }
}

class Right {
  constructor(value) { this.value = value; }
  map(fn) { return new Right(fn(this.value)); }
  flatMap(fn) { return fn(this.value); }
  getOrElse(def) { return this.value; }
  isLeft() { return false; }
  isRight() { return true; }
  toString() { return "Right(" + JSON.stringify(this.value) + ")"; }
}

function validateSample(sample) {
  if (!sample.id) return new Left("Missing sample ID");
  if (sample.purity < 0.5) return new Left("Purity too low: " + sample.purity);
  if (!sample.species) return new Left("Unknown species");
  return new Right(sample);
}

function processSample(sample) {
  return validateSample(sample)
    .map((s) => ({ ...s, processed: true }))
    .map((s) => ({ ...s, label: s.species + "-" + s.id }));
}

const good = processSample({ id: "S01", purity: 0.95, species: "T-Rex" });
console.log("Success:", good.toString());
console.log("Value:", JSON.stringify(good.getOrElse("ERROR")));

const bad1 = processSample({ id: "", purity: 0.95, species: "T-Rex" });
console.log("\nFail 1:", bad1.toString());

const bad2 = processSample({ id: "S02", purity: 0.3, species: "Raptor" });
console.log("Fail 2:", bad2.toString());

// --- EXAMPLE 4: An Either chain ---
console.log("\n--- Either chain ---");

function parseInput(raw) {
  try { return new Right(JSON.parse(raw)); }
  catch (e) { return new Left("Parse error: " + e.message); }
}

const pipeline = (raw) =>
  parseInput(raw)
    .flatMap((data) => data.name ? new Right(data) : new Left("Missing name"))
    .map((data) => ({ ...data, status: "validated" }));

console.log(pipeline('{"name":"Rex"}').toString());
console.log(pipeline('{"age":5}').toString());
console.log(pipeline('invalid json').toString());

Docs entries used in this lesson

Spotted a mistake in this lesson?

Check yourself

Answer the questions from this lesson. Pick an answer to see right away whether it is correct.

  1. 1. What must an object implement to be a functor?

  2. 2. What does Array.flatMap() return compared to Array.map()?

These are 2 of 3 questions for this lesson. Solve the rest in the game.

Hands-on tasks in the game

  • Vertical ordering

    Arrange the steps for safely retrieving data using Maybe:

  • Horizontal ordering

    Arrange the elements of a flatMap call on Maybe:

  • Horizontal ordering

    Arrange the elements of a Maybe chain for safely extracting data:

  • Click in order

    Arrange the elements of validation with Either:

  • Vertical ordering

    Arrange the pillars of functional programming from most fundamental:

  • Code editor

    Implement safe data lookup and validation using Maybe and Either.

  • Vertical ordering

    Arrange the elements of a memoize implementation with closure:

  • Click in order

    Arrange the elements of array grouping with reduce:

  • Vertical ordering

    Arrange the stages of building a functional data processing pipeline:

  • Horizontal ordering

    Arrange the elements of a partial application implementation:

  • Click in order

    Arrange the elements of a filter-map-reduce pipeline:

  • Vertical ordering

    Arrange the stages of refactoring from imperative to functional code:

  • Vertical ordering

    Arrange the layers of a functional data processing pipeline from input to output:

  1. QuestionFunctor
  2. Put in orderProcessing with Maybe
  3. Put in orderflatMap Syntax on Maybe
  4. Put in orderMaybe Chaining Syntax
  5. Click in orderValidation with Either
  6. QuestionArray.flatMap() vs Array.map()
  7. Put in orderPrinciples of Functional Programming
  8. Coding taskMaybe and Either in Practice
  9. Put in orderMemoize Syntax with Closure
  10. Click in orderPipeline with reduce
  11. Put in orderStages of Building an FP Pipeline
  12. QuestionObject.freeze() vs const
  13. Put in orderPartial Application Syntax
  14. Click in orderfilter-map-reduce Chain
  15. Put in orderStages of Refactoring to Functional Style
  16. Put in orderLayers of a Functional Data Pipeline

Useful articles