Idiomatic way to test for non-nullishness

287 views Asked by At

JavaScript now provides ?? and ?. to do things like find the first non-nullish expression or dereference an object if not null.

[Added: "nullish" means "null or undefined", like the nullish coalescing operator].

Is there a good idiomatic way to simply test for non-nullishness? For instance, if I want to only call an onChange() handler if my value is non-nullish. That is:

someVal && onChange(someVal)

Obviously this is incorrect, because it would fail for falsy but non-nullish values (notably 0 and '').

1

There are 1 answers

1
Bergi On BEST ANSWER

The idiomatic way is an if statement with a comparison against null:

if (someVal != null) onChange(someVal)
if (someVal != null) {
    onChange(someVal)
}

There is no operator for this. Some people have expressed as desire for an extension to the pipeline operator proposal that would let you write you something like someVal ?> onChange;, but I don't know of any implementation of that idea.