1

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 '').

Steve Bennett
  • 114,604
  • 39
  • 168
  • 219

1 Answers1

1

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.

Bergi
  • 630,263
  • 148
  • 957
  • 1,375