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;
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With