2

Is there a way to implement or apply nullish-coalescing for undeclared variables?

let a;
a ?? 'Text' // Returns 'text'

//Expected
b ?? 'Text' //Should Return 'text' 
mplungjan
  • 169,008
  • 28
  • 173
  • 236
Nish
  • 353
  • 3
  • 9
  • 1
    Seems pretty clear to me... `a` is defined, it is just "undefined", the placeholder for an unallocated value. `b` is not defined, literally it does not exist in the current memory environment, so a lookup failure occurs and you see that error as a result of not finding the memory location. – Travis J Feb 17 '21 at 18:42
  • If you want to determine variable existence the best you'll be able to do is check whether *only global* variables are defined (with `window.hasOwnProperty('varName')` (browser) or `global.hasOwnProperty('varName')` (node)). Also, I would never personally approve of any software logic which depends on checking for variables existence. – Gershom Maes Feb 17 '21 at 23:48

1 Answers1

-1

The way you can check variables that are not defined is by checking that they have an undefined typeof:

let a;

console.log(a || 'text') // prints 'text'

console.log((typeof b !== 'undefined' && b) || 'text') // also prints 'text'

let c = 'other text'
console.log((typeof c !== 'undefined' && c) || 'text') // prints 'other text'
Lucas Bernalte
  • 1,179
  • 11
  • 17