From MDN:
The nullish coalescing operator (
??
) is a logical operator that returns its right-hand side operand when its left-hand side operand isnull
orundefined
, and otherwise returns its left-hand side operand.
However, the following statement doesn't seem to work if the variable isn't declared:
console.log(foobar ?? 555);
// Uncaught ReferenceError: foobar is not defined
If I explicitly declare the variable, it works:
let foobar;
console.log(foobar ?? 555);
// 555
The only alternative appears to be:
console.log(typeof foobar !== 'undefined' ? foobar : 555)
// 555
Is there a cleaner way to check if something is undeclared and return a fallback value?
I know there's an argument against why code would check for a variable that wouldn't be declared. For example, the following function accepts a parameter without assigning it a default value, making ??
seem useful:
const baz = (foobar) => (`${foobar ?? 555}baz`) // same as: const baz = (foobar = 555) => (`${foobar}baz`);
baz()
// 555baz
Is this scenario the intended use of this operator? If it is, then also be served by assigning the argument a default value in the signature, so how does the nullish coalescing operator differ itself in usefulness?
Note: The statements above were run in Node.js 14 as well as Chrome 88.