Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it valid to use undefined as a last operand of OR operator in order to assign value?

Tags:

javascript

Is it valid to write code below in order to get undefined (not false) in the result in any circumstances when the first operand is falsy? Regardless of JavaScript version and regardless of the browser and its version.

let someFalsyValue = "";
let result = someFalsyValue || undefined;
like image 393
Aleksandrs Tukans Avatar asked Mar 02 '23 21:03

Aleksandrs Tukans


2 Answers

Your approach is safe.

logical OR || returns the first truthy value or the last truthy/falsy value.

It has been in the standard of the very first version of ECMA-262, 1st edition, June 1997 in chapter 11.11 Binary logical operators.

like image 132
Nina Scholz Avatar answered Mar 05 '23 18:03

Nina Scholz


It is, and has always been, reliable to use the || operator in this way.

The global undefined property, (which contrary to the belief of many JS users, is not a special literal defined in the language syntax like null) has a more complex history. In older browsers, there was no guarantee that the value of window.undefined was actually, well, undefined, as any code could set it. Therefore it was customary to use the void operator instead, or work inside the scope of a function where one of the arguments was known to be unspecified by the caller, and thus have the value undefined.

like image 35
Jonas Høgh Avatar answered Mar 05 '23 17:03

Jonas Høgh