DEV Community

Joshua Amaju
Joshua Amaju

Posted on

Representing missing values

We all have to deal with missing values i.e null, which was later said to be a billion dollar mistake. Missing values are usually represented as null or undefined, but depending on your application needs, an empty string or zero might also be considered a missing value.

The conventional way is to

if (someValue !== null && someValue !== undefined) {
}
Enter fullscreen mode Exit fullscreen mode

and maybe some more

if (
  someValue !== null &&
  someValue !== undefined &&
  someValue !== someString.trim()
) {
}

// or

if (someValue && someValue.trim() !== "") {
}
Enter fullscreen mode Exit fullscreen mode

or maybe with fancy new JavaScript

let a = someValue ?? defaultValue;
Enter fullscreen mode Exit fullscreen mode

or maybe the old way

let a = someValue || defaultValue;
Enter fullscreen mode Exit fullscreen mode

But in my opinion, they don't give a wholesome way of dealing with missing values.

A better option is to use Optionals (no pun intended) to denote missing values (the most benefit comes with Typescript) and handle situations where an empty string or zero might be a missing value, by applying a predicate that returns an optional e.g

let name: Option<string> = O.none; // there's no value for name denoted by a `none`;

if (Option.isSome(name)) {
  // `name` has a value, do something with the value of `name`
}
Enter fullscreen mode Exit fullscreen mode

and

// name must not be an empty string, if it is, return a `none` (no value). If name has a value, we get a `some` (some value)
const transformed = Option.fromPredicate((n) => n.trim() !== "")(name);
Enter fullscreen mode Exit fullscreen mode

Which makes more sense from a linguistic point of view, a missing value is nothing/none. Want to learn more? check out fp-ts

Top comments (0)