5

From MDN:

The nullish coalescing operator (??) is a logical operator that returns its right-hand side operand when its left-hand side operand is null or undefined, 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.

aalaap
  • 4,145
  • 5
  • 52
  • 59
  • 4
    No, not really. Conditional operator is the way to go here. But dynamic variable names are quite a code smell and usually shouldn't be present in decently-maintained code anyway. – CertainPerformance Feb 08 '21 at 06:22
  • Yeah, that's the argument I was referring to. The more I fleshed out the question, the more the answer became apparent. – aalaap Feb 08 '21 at 06:25
  • You can use `globalThis.foobar ?? 555` or `window.foobar` in Chrome specifically. – Uahnbu Tran Aug 06 '21 at 14:21

0 Answers0