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) {
}
and maybe some more
if (
someValue !== null &&
someValue !== undefined &&
someValue !== someString.trim()
) {
}
// or
if (someValue && someValue.trim() !== "") {
}
or maybe with fancy new JavaScript
let a = someValue ?? defaultValue;
or maybe the old way
let a = someValue || defaultValue;
But in my opinion, they don't give a wholesome way of dealing with missing values.
A better option is to use Option
als (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`
}
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);
Which makes more sense from a linguistic point of view, a missing value is nothing/none. Want to learn more? check out fp-ts