JS Blog Software development, entertainment, lifestyle.

Maybe

M

In functional programming, Maybe is a wrapper around a value which deals with null or undefined values for you. That means if you get that kind of value as a result of some computation, all other chained operations that follow, evaluate to that value. It turns if/else where you check for value’s nullness or undefined value into functions.

For example, if you are querying for a user and user is null, then you wouldn’t want to get an avatar for a non-existing user. In that case, you’d perhaps want to return some default avatar (orSome according to monet.js API). Or if you are querying for user’s name and because there isn’t one set, you’d want to get its nickname instead (orElse, which computes and returns another Maybe). If also no nickname is present than you’d want to return some default value (i.e. “Guest”, again use orSome).

When you finally want to use that Maybe value, use a method on Maybe that takes two callbacks: first for null/undefined case, second for a value. This method is typically called cata ((This word stands for catamorphism – I still don’t know what the heck does it actually mean.)).

Read this article for more (with code examples).

By Jernej
JS Blog Software development, entertainment, lifestyle.

About me

Jernej Sila portrait
Hi, I'm Jernej, a software engineer from Slovenia. Welcome to my personal blog. For more about me, my work and hobbies, please visit my profile page.

Categories

Archives