Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I write an || expression in Javascript where 0 isn't treated as a falsy value?

Tags:

javascript

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.

like image 978
Joey Avatar asked Jun 16 '12 19:06

Joey


2 Answers

All you need to do is write a helper function...

function ifNotSet(val, other) {
    return typeof val === "undefined" ? other : val;
}
like image 59
Matt Avatar answered Sep 25 '22 17:09

Matt


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.

like image 32
Sarfraz Avatar answered Sep 23 '22 17:09

Sarfraz