Monad in JavaScript

Monads are a powerful concept in functional programming, often used in JavaScript to manage side effects, handle errors, and compose functions in a clean and modular way. They encapsulate values and provide methods to apply functions to these values while maintaining the monadic context. This allows for safe chaining of operations and managing data flow without explicit error handling code. Monads are a type of functor that allow for more complex operations, often used for tasks like data validation, error handling, and null checks.

Monad Components

Monads consist of several key components that enable their functionality:

  1. Type Constructor: This is used to create a new monadic type. For example, in the Wrapper monad, the type constructor is the class itself.

  2. Unit Function: Often called of, this function takes a value and returns it wrapped in a monad. It is used to lift a value into the monadic context.

  3. Bind Function: Also known as map or flatMap, this function applies a function to the value inside the monad and returns a new monad. It allows for function composition within the monadic context.

  4. Join Operation: This operation is used to flatten nested monadic structures, ensuring that the result remains within a single monadic layer.

Example: Wrapper Monad

The Wrapper monad is a simple example that demonstrates these components:

class Wrapper {
    constructor(value) {
        this._value = value;
    }
    static of(a) {
       return new Wrapper(a);
    }
    map(f) {
      return Wrapper.of(f(this.value));
    }
    join() {
      if(!(this.value instanceof Wrapper)) {
         return this;
      }
      return this.value.join();
    }
    toString() {
      return `Wrapper (${this.value})`;
    }
}
  • Type Constructor: Wrapper class
  • Unit Function: static of(a)
  • Bind Function: map(f)
  • Join Operation: join()

Maybe Monad

The Maybe monad is used to handle nullable values, providing a way to safely chain operations without explicit null checks. It has two subtypes: Just, which contains a value, and Nothing, which represents the absence of a value.

Implementation of Maybe Monad

class Maybe {
  static just(a) {
     return new Just(a);
  }
  static nothing() {
     return new Nothing();
  }
  static fromNullable(a) { 
     return a !== null ? just(a) : nothing();
  }
  static of(a) {
     return just(a);
  }
  get isNothing() {
     return false;
  }  
  get isJust() {
     return false;
  }
}
class Just extends Maybe {
   constructor(value) {
      super();
      this._value = value;
   }
   get value() {
      return this._value;
   }   
   map(f) { 
      return of(f(this.value));
   }
   getOrElse() {
      return this.value;
   }
   filter(f) {
      Maybe.fromNullable(f(this.value) ? this.value : null);
   } 
   get isJust() {
     return true;
   }
   toString () {
     return `Maybe.Just(${this.value})`;
   }   
}
class Nothing extends Maybe {
   map(f) {
    return this; 
   }
   get value()  {
     throw new TypeError('Can't extract the value of a Nothing.');
   }
   getOrElse(other) {
     return other;
   }  
   filter() {
     return this.value;
   }
   get isNothing() {
      return true;
   }
   toString() { 
    return 'Maybe.Nothing';
  }
}

Either Monad

The Either monad is used to handle computations that may fail, providing a way to encapsulate both successful and failed computations. It has two subtypes: Left, which typically holds an error, and Right, which holds a successful value.

Implementation of Either Monad

class Either { 
  constructor(value) {
     this._value = value;
  }
  get value() {
     return this._value;
  }
  static left(a) {
    return new Left(a); 
  }
  static right(a) {
    return new Right(a);
  }
  static fromNullable(val) {
     return val !== null ? right(val): left(val);
  }
  static of(a){
     return right(a);
  }
}
class Left extends Either {
   map(_) {
    return this; // noop
   }
   get value() {
      throw new TypeError('Can't extract the value of a Left(a).');
   }
   getOrElse(other) { 
      return other;
   }
   orElse(f) {
      return f(this.value);
   }
   chain(f) {
      return this; 
   }
   getOrElseThrow(a) {
      throw new Error(a);
   } 
   filter(f) {
      return this; 
   }
   toString() {  
     return `Either.Left(${this.value})`;
   }
 }
class Right extends Either {
    map(f) {
       return Either.of(f(this.value)); 
    }
    getOrElse(other) { 
       return this.value;
    }
    orElse() {
       return this; 
    }    
    chain(f) {
       return f(this.value);
    }
    getOrElseThrow(_) {
       return this.value;
    }
    filter(f) {
        return Either.fromNullable(f(this.value) ? this.value : null);
    }
    toString() {  
        return `Either.Right(${this.value})`;
    }
 }

Monad Usage

Monads allow for chaining and composing functions in a way that manages side effects and errors gracefully. They enable the creation of pipelines where each function can handle its own errors and pass results to the next function, maintaining a clean and modular code structure.

Example: Refactoring Functions to Use Either

// validLength :: Number, String -> Boolean
const validLength = (len, str) => str.length === len;     
// checkLengthSsn :: String -> Either(String)
const checkLengthSsn = function (ssn) {
    return Either.of(ssn).filter(_.bind(validLength, undefined, 9))
       .getOrElseThrow(`Input: ${ssn} is not a valid SSN number`);
};
// safeFindObject :: Store, string -> Either(Object)
const safeFindObject = R.curry(function (db, id) {
    return Either.fromNullable(find(db, id))
       .getOrElseThrow(`Object not found with ID: ${id}`);
});
// findStudent :: String -> Either(Student)
const findStudent = safeFindObject(DB('students'));
// csv :: Array => String
const csv = arr => arr.join(',');

Visual Representation

Monads can be visually represented to show their flow and structure. For example, the flow of a function using monads can be depicted as follows:

Figure 5.12 Figure 5.12. Step-by-step flow of the showStudent function in the case where findStudent successfully finds a student object by the provided SSN

| Book Title | Usage of Monad | Technical Depth | Connections to Other Concepts | Examples Used | Practical Application |
|------------|----------------|-----------------|-------------------------------|---------------|-----------------------|
| [Functional Programming in JavaScript](https://www.manning.com/books/functional-programming-in-javascript) | Monads are used to structure programs with side effects, manage errors, and compose functions. They encapsulate values and provide methods to apply functions while maintaining the monadic context. [more](https://livebook.manning.com/book/functional-programming-in-javascript/chapter-5/94) | Discusses monad components like type constructor, unit function, bind function, and join operation. [more](https://livebook.manning.com/book/functional-programming-in-javascript/chapter-5/127) | Connects monads to concepts like Maybe and Either monads, showing their use in handling nullable values and computations that may fail. [more](https://livebook.manning.com/book/functional-programming-in-javascript/chapter-5/140) | Provides examples like the Wrapper, Maybe, and Either monads, with code snippets for implementation. [more](https://livebook.manning.com/book/functional-programming-in-javascript/chapter-5/127) | Demonstrates practical applications in refactoring functions to use Either for error handling and data validation. [more](https://livebook.manning.com/book/functional-programming-in-javascript/chapter-5/245) |
| [The Joy of JavaScript](https://www.manning.com/books/the-joy-of-javascript) | Monads are described as a type of functor for complex operations like data validation and error handling, allowing for compositional chaining. [more](https://livebook.manning.com/book/the-joy-of-javascript/part-2/1) | Covers the monad mixin, showing how `flatMap`, `chain`, and `bind` methods are used for chaining operations. [more](https://livebook.manning.com/book/the-joy-of-javascript/chapter-5/144) | Discusses the composition with functors and emulating typeclasses to integrate monadic behavior into types. [more](https://livebook.manning.com/book/the-joy-of-javascript/chapter-5/144) | Provides a Monad mixin example, demonstrating how to use `flatMap` and integrate with functors. [more](https://livebook.manning.com/book/the-joy-of-javascript/chapter-5/144) | Shows how to extend types with the Monad mixin for structured and flexible code, similar to using `Array#{map, filter, reduce}`. [more](https://livebook.manning.com/book/the-joy-of-javascript/part-2/1) |

FAQ (Frequently asked questions)

How do monads allow for chaining operations?

How do monads enable chaining of computations?

What are alternative names for the chain method in a monad?

What methods do monads provide to apply functions to values?

What interface do monads implement?

What kind of protocols do monads support?