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'
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'
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'