Please forgive my English. I am not a native speaker.
My problem comes when I write code like this
luminosity = settings.luminosity || 50;
opacity = settings.opacity || 100;
The problem is that 0
is supposed to be a valid value, but it will be overlook because 0
is falsy in Javascript and it will set to the default value on the right of ||
.
Is there a way to do a fix so 0
isn't treated as falsy?
Right now I am doing
luminosity = "luminosity" in settings ? settings.luminosity : 50;
but I don't like that because it is so long.
All you need to do is write a helper function...
function ifNotSet(val, other) {
return typeof val === "undefined" ? other : val;
}
You can convert it to string '0'
is truthy
:
luminosity = settings.luminosity === 0 ? '' + settings.luminosity : settings.luminosity || 50;
opacity = settings.opacity === 0 ? '' + settings.opacity : settings.opacity || 100;
Or you can simply use this depending on your input or requirement:
luminosity = '' + settings.luminosity || 50;
opacity = '' + settings.opacity || 100;
'' + number
is shorthand for converting a number to string.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With