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.