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

Sentry image

Hands-on debugging session: instrument, monitor, and fix

Join Lazar for a hands-on session where you’ll build it, break it, debug it, and fix it. You’ll set up Sentry, track errors, use Session Replay and Tracing, and leverage some good ol’ AI to find and fix issues fast.

RSVP here →

Top comments (0)

Cloudinary image

Video API: manage, encode, and optimize for any device, channel or network condition. Deliver branded video experiences in minutes and get deep engagement insights.

Learn more

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay