Photo by Joan Gamell on Unsplash

How to avoid null and undefined by using Maybe and Result (Either) in javascript

There are many tools, functions, and techniques to evaluate if a variable exists if it is well defined and not null. While working on a project following the functional programming paradigm, I practiced one that deserves special attention.

Case 1: Optional field

I want to test in my backend the content of a non-mandatory form field from the frontend.

  • Just() : a value
// myVariable comes from the formmyVariable.matchWith(Nothing : () => queFaireSiAucuneValeur(),Just : dataObject => traitementAAppliquer(dataObject.value)});
// myVariable contains Maybe.Nothing()myVariable.isJust //falsemyVariable.isNothing //true

Case 2: The result of a query to the DB

I want to evaluate a DB query result and have either a value or an error.

  • Ok() : to contain the result
myVariable.matchwith(Error: err => fonctionDeGestionErreur(err.value),Ok: result => traitementAAppliquer(result.value)});

Practical examples

To implement these examples, you need to create a node.js project using NPM :

  1. In this directory run the command npm init.
  2. Follow the wizard
  3. Install Folktale: npm install --save folktale
  4. Open index.js in an editor

Maybe() example

const Maybe = require(‘folktale/Maybe’);// const variable = Maybe.Nothing();const variable = Maybe.Just(‘great value’);variable.matchWith(Nothing: () => console.log(‘Sorry, no value here’),Just: dataObject => console.log(‘Value is : ‘ + dataObject.value),});

Result() example

const Result = require(‘folktale/Result’);// const variable = Result.Error(‘this is an error !’);const variable = Result.Ok(‘Expected result’);variable.matchWith(Error: err => console.log(err.value),Ok: dataObject => console.log(‘Value is : ‘ + dataObject.value),});

Conclusion

I did not have to deal with undefined or null values with these methods. It requires some preliminary work when defining the values or the data retrieval functions, but in the end, it's very comfortable to use!

Product guy who likes technology, Apple, apps, gadgets and cats