Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Javascript OR Expression: return Operand that is *not* NaN

I have an OR expression that should return the operand that is anything else than NaN:

(1 || NaN) // evaluates to 1 
(NaN || 1) // evaluates to 1

But when the other operand is also a falsy value like 0, null, undefined or false, Javascript returns always the rightmost operand:

(0 || NaN) // evaluates to NaN
(NaN || 0) // evaluates to 0
// same for combinations of 0, null, undefined and false

Is there a way to fit the desired behaviour "Return the operand that is not NaN" into a nice & short expression or do I have to rely on an if/else construct?

like image 589
Benni Avatar asked Mar 19 '26 14:03

Benni


1 Answers

You could add a default falsy value at the end of the expression, like

result = yourValue0 || yourValue1 || 0;

In this case, you get either a truthy value of yourValueX or the last falsy value.

like image 73
Nina Scholz Avatar answered Mar 21 '26 02:03

Nina Scholz