Search code examples
javascriptreadabilitysyntactic-sugar

Is it worth the effort to have a function that returns the inverse of another function?


I have recently added a HasValue function to our internal javascript library:

function HasValue(item) {
    return (item !== undefined && item !== null);
}

A during a convorsation with a coworker, we came up with the idea of also adding another function that would basically just be the inverse: perhaps HasNoValue, or IsNothing If we ended up doing that we would have:

function HasNoValue(item) {
    return (item === undefined || item === null);
}
function HasValue(item) {
    return !HasNoValue(item);
}

However, we're not sure whether it is more readable to have both, or HasValue. Which is more readable/preferred?

A:

if (HasValue(x) && !HasValue(y))

B:

if (HasValue(x) && HasNoValue(y))

Solution

  • I vastly prefer A to B. "!" is a programming idiom that should be understood by all.