Functional Javascript — Null, Undefined and the Option Pattern

Tibor Botos
5 min readFeb 8, 2016

--

In my previous post I was showing what are the basics of the functional javascript programming. This time I try to introduce the optional pattern, and how can be a solution of repeating null checking.

There are a lot of articles about javascript null and undefined. What are differences, how to equality check them, how you should handle them. At this point I assume you are pretty familiar with javascript and programming in general, and know what’s the difference between a null and an undefined. If you are not sure check this for a quick catch-up.

Manage an empty value

Let’s start with a simple example, where we have a person object and in this we store the name of this person. Our goal is to display the name of this person, so let’s write a null safe formatter function.

That’s a pretty simple code, just checking for nulls. Is it a good solution? What’s going to happen if I call formatName with person2?

undefined Bill undefined undefined

Now it’s a good time to talk about a semantic difference between undefined and null. Null is explicitly set, while undefined is just something that’s not set. We must ask ourselves if there is a scenario when the name fields are not explicitly set? Yes, there is.

Check the code at http://jsbin.com/kayareg/edit?html,js,output

In an ideal world every developer would create the correct new person function, which sets every empty value to null. However it would be cumbersome to do that.

The first and biggest issue that we don’t know what should an ideal object look like. This is because javascript is a non typed language, meaning we don’t necessarily have definition for every field of an object. Or in other words we don’t have documentation of the classes (objects). Obviously this problem can be solved by well documented code, or using factory classes for empty instance creation or strict coding policies or with an advanced IDE and so on. But if more than one person is working on a project it’s almost impossible to follow these rules. That’s why it’s so reasonable for every javascript developer to see lines like

if (typeof person.title !== 'undefined' && person.title !== null) {
...
}
Javascript can be really confusing

Avoid complexity, simplify

I believe the code above suits a good goal, and make our software error prone. But I just hate it. Why do I need such large if conditions only to check if there is something. I generally like to avoid if conditions, because the less the conditions the less branch I have to unit test. So how to simplify this expression?

  • for those who are targeting ES5+ browsers stop using typeof. Undefined is read only,
  • use framework validators, like angular’s or underscore’s isUndefined helper,
  • documentation helps, but keeps you busy updating it. Use jsdoc on API level when you believe it’s done,
  • and most importantly stop using null in javascript.

In the past couple of years I was working with Java backend, where there is no such thing as undefined, and just the concept itself was enough to brain freeze all the Java developers. They can only think about nulls and Long and Integer and strongly typed generics hell. But in javascript null is the strangest thing. Starting with the fact that null is an object.

It’s just pure evil

The other thing that null can only be set by a human. It’s actually called null reference meaning that an object pointing to the empty vacuum of the RAM. There is a javascript equivalent for that. It’s called undefined. So as a thumbs up rule I recommend not using null at all*.

(*[small print] obviously there can be some exception, but I suggest to think about it, that you really need to use null)

Here comes the functional paradigm

After we feel pretty confident about null and undefined we should start talking about how we can turn the not existing phenomenon into a functional programming solution. It’s often called the maybe pattern (monad) or the option pattern. Here you can find my AngularJS service implementation.

In this example you can see, this is just a wrapper class around a value, which gives you the ability to map and check the value of it. But with this little functionality we can map the value of each fields and return of it in a safe way, saying if it’s empty we would like to receive an empty string.

While it doesn’t seem we made a huge simplification we must see the bigger picture. With the elimination of null checking you can make cleaner code. Which means easier reading and understanding and easier bug fixing. But we need to clarify. If we have user input and/or a backend, we will definitely need null checking. All we can do is limiting the number of null checks and the well known error message “undefined is not a function”.

The Option type is working pretty well with Typescript, where the type declaration itself is a great indirect documentation of the code.

Take a step forward

There are a lot of javascript maybe implementation, but I raise it with a collection handling library. A practical reason you need such library could be

  • filtering by a value or a function,
  • making a list unique,
  • finding an item in a list by a value or a function, where you may find or not find a value,
  • returning the first or last value if there is.

If you think about it the option pattern is really useful in the last 2 case, where they might be an empty result. So we don’t need to depend on null checking. How? Coding time!

Final notes

I expect confusion. Maybe not everything is clear, because I wanted to make it short, but include everything useful. This is a thing which works better if you do it, and not just read it. So I encourage to do that, and try in your hobby project. Find some time to understand the reasoning, to become a better developer. I know a lot of great developer, and I believe only a small step is required to be a better, functional javascript developer.

Currently I am working on RealTime Oncology Calculator as a Front end engineer in Budapest, Hungary. This is an online computational tool, a unique adaptive search engine and collaborative learning system for precision oncology. Our aim is to find the best personalized treatment based on the molecular alterations to beat cancer once and for all.

--

--

Tibor Botos

Senior Front End engineer, passionate about user experience, reliable, well tested code and the future of application development