Nullish Coalescing

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

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

b ?? 'Text' //Should Return 'text' 

3 thoughts on “Nullish Coalescing”

  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'

Leave a Comment