0

In Javascript, I can use the || operator to provide a default value anywhere when a given value is undefined or null

let a = maybeUndefinedValue || 'my default value'
foo(arg1, arg2 || 'default', arg3)
bar = settings.getSync('key') || 'default value'

However, this would not work for booleans, as both a false and an undefined value would trigger the default value to be used. For example, I want to use the default value only when the settings is missing, but not when the settings is set to false. If I use

let mySettings = settings.getSync('aBooleanKey') || true

Even when the settings is present and is set to false, it'll still fall back to true. I could use

let mySettings = settings.getSync('aBooleanKey') == undefined ? true : settings.getSync('aBooleanKey')

But this feels extra as I'm calling the function twice. Is there an elegant solution to providing a default value ONLY when it's undefined and not false in Javascript just like the || operator? By elegant I mean I don't have to call the function twice or use an intermediate variable.

isherwood
  • 58,414
  • 16
  • 114
  • 157
Nicholas
  • 747
  • 7
  • 23
  • you can use the [nullish coalescing operator (??)](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Nullish_coalescing) to check only undefined and null – pilchard Jan 19 '23 at 17:53
  • 1
    `const a = whatever() ?? defaultValue` – Jared Smith Jan 19 '23 at 17:55

0 Answers0