How to write || expression in javascript where 0 is not considered to be a fake value?

Please forgive my English. I am not a native speaker.

My problem arises when I write code like this

luminosity = settings.luminosity || 50;
opacity = settings.opacity || 100;

The problem is what 0should be a valid value, but it will be ignored because it 0is false in Javascript and it will set the default value to the right of ||.

Is there a way to make a correction, so it is 0not considered a lie?

I'm doing now

luminosity = "luminosity" in settings ? settings.luminosity : 50;

but I don’t like it because it takes so long.

+5
source share
4 answers

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

function ifNotSet(val, other) {
    return typeof val === "undefined" ? other : val;
}
+2
source

'0' is truthy:

luminosity = settings.luminosity === 0 ? '' + settings.luminosity : settings.luminosity || 50;
opacity = settings.opacity === 0 ? '' + settings.opacity : settings.opacity || 100;

:

luminosity = '' + settings.luminosity || 50;
opacity = '' + settings.opacity || 100;

'' + number .

+2

A common default install / setup .extend()method is a method in jQuery . Pure JS also has this method, but with some others.

/* merge object2 into object1 */
$.extend(object1, object2);

This is what you need:

var defaultSetting = {luminosity : 50, opacity : 100};
setting = $.extend({}, defaultSetting, setting);
+2
source

Setting up the initial version of @Tooraj code:

var setting = {luminosity:0};
var defaultSetting = {luminosity:50, opacity:100};

setting = $.extend({}, defaultSetting, setting);

// setting now has a value of {luminosity:0, opacity:100}

I haven’t done this before. But it seems to work fine in FF, Chrome, and IE9.

+1
source

All Articles