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?
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);
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