0

Consider a variable master which can be true or false, never anything else.

Consider another variable override which can be undefined, true or false.

So how to determine which variable to use, if override is not undefined then use that otherwise use master.

Maybe we could do:

if ((master !== undefined && master) || override) then
   ...

But is this correct and also is there a better way?

j08691
  • 204,283
  • 31
  • 260
  • 272
AJ.
  • 10,732
  • 13
  • 41
  • 50

5 Answers5

1
if( typeof override !== "undefined" ? override : master)

It's an unconventional use of the ternary operator, but it does exactly what you want:

If override is defined, use it. Otherwise, use master. If the chosen one is true, then...

Niet the Dark Absol
  • 320,036
  • 81
  • 464
  • 592
1

You said that:

  • master can only be true or false
  • override can be true, false or undefined
  • if override is not undefined then use it

So the correct code will be:

if (typeof override !== "undefined" ? override : master) {
    // use override
} else {
    // use master
}
Marco Bonelli
  • 63,369
  • 21
  • 118
  • 128
0

Something like this should work for you

if ((override === undefined && master) || (override !== undefined && override)) {
     ...
}
RaYell
  • 69,610
  • 20
  • 126
  • 152
0

Similar to what Niet said, but I think it's clearer to store it in a variable.

var _set = ( typeof override !== 'undefined' ? override : master );

if ( _set ) {
   ...
}
vol7ron
  • 40,809
  • 21
  • 119
  • 172
0

I'd do it in this way, which is more clear and easier to read.

var usethis;
if (typeof override != 'undefined') {
  usethis = override;
} else {
  usethis = master;
}

if (usethis) {
  // Enable feature X
}

You first check if the override variable is defined: if so we'll use that value, otherwise fall back to master. Then you actually use the value to enable a feature (I suppose that's your use case).

If you want, you can write that in this more compact way:

var usethis = typeof override != 'undefined' ? override : master;

if (usethis) {
  // Enable feature X
}

You have to use the typeof operator, otherwise type coercion will cast the override variable to boolean value, and you miss the false value.

Alessandro Vendruscolo
  • 14,493
  • 4
  • 32
  • 41