1

I have a function that may return a value or may return null and I want to assign it to a variable. So at the moment I've got

someVar = (someFun())
  ? someFun()
  : "foo";

Is there a shorterer way of doing it, where I don't have to call the function twice, or add an extra variable like:

funResult = someFun();
someVar = (funResult)
  ? funResult
  : "foo";

Basically, something like:

someVar = someFun() | "foo"
stib
  • 3,346
  • 2
  • 30
  • 38

1 Answers1

1

The idiomatic way is

someVar = someFun() || "foo";

The || operator will yield the value of the left-hand expression if it's truthy. If not, it will move on to evaluate the right-hand side, and return its value.

For those unfamiliar with the term "truthy", in JavaScript it means values that are not considered by the language to be implicitly false. The implicitly false values are 0, NaN, false (of course), "", null, and undefined. Any reference to an object, even if it's completely empty, is considered to be "truthy".

In your specific example, the || approach is to be preferred because it means you only call someFun() once.

Pointy
  • 405,095
  • 59
  • 585
  • 614