3

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?

Wray Bowling
  • 2,346
  • 2
  • 16
  • 19

1 Answers1

4

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);
PSL
  • 123,204
  • 21
  • 253
  • 243
  • 3
    Remove `args` and just reference `arguments`. You aren't using any array methods, so you don't need to "convert" it in this way. – Niet the Dark Absol Nov 04 '13 at 22:40
  • 2
    I call this method `default` and use it in my code. The only difference I don't check against null because `null` _is_ a value (since not being defined and being explicitly nothing are different things imo. This is the better approach if you want to check things that are not just objects :) – Benjamin Gruenbaum Nov 04 '13 at 22:50
  • @BenjaminGruenbaum hmmm right! but just checking to ensure null in case that is set explicitly.. but moving it as second condition will make more sense as it is less likely to happen that something not defined. – PSL Nov 04 '13 at 22:56
  • I agree with bejamin. if something is null, then it was set BY ME as null. undefined is the only thing i'd skip over because there's nothing to use. in practise, if none of the values passed in to default are defined, then i'll return null. this is wonderful help, you all. thanks! – Wray Bowling Nov 05 '13 at 14:19
  • Feel funny about editing this, but i did. please correct me if I went too far! – Wray Bowling Nov 05 '13 at 14:45