Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

javascript: set a variable to the first available value

Tags:

javascript

In CSS you might set a property like font-family to a list of comma-separated things and the first thing found is used.

font-family: Fancy Font, Arial, sans-serif;

In Javascript, I've started to grow accustomed to using a double-bar logical OR as a way to set a variable to the first available value.

var x = parameters.x || user_default.x || 123;

the problem I've found is that || evaluates 0 as false which skips over that value. Perhaps it's a pipe dream, but is there an elegant similar syntax I can use without resulting in these false positives?

like image 696
Wray Bowling Avatar asked Aug 13 '26 17:08

Wray Bowling


1 Answers

You cannot do it with a simple || operator because in js 0 is falsy (along with "", undefined, null and false), so it will fail the condition. You can write a simple utiltiy function like this.

function tryGetValue() {
    var val;
    for (var i = 0, l = arguments.length; i < l; i++) {
        val = arguments[i];
        if (val !== undefined && val !== null) //check only for null & undefined, you can also do if (val != null) which will check for both null and undefined but it will fail in jslint validation.
        return val;
    }
}

Usage:

var x = tryGetValue(parameters.x, user_default.x , 123);
like image 110
PSL Avatar answered Aug 16 '26 07:08

PSL