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
  • 155,085
  • 27
  • 166
  • 222
Nish
  • 333
  • 2
  • 8
  • 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
  • 859
  • 8
  • 15