Hevar Hevar - 1 year ago 42
Javascript Question

Alternative to multiple if statements?

This just feels inefficient and ugly:

if(foo("val1")) {
let val1 = foo("val1")
}

if(foo("val2")) {
let val2 = foo("val2")
}

/* more IFs */

if(foo("val13")) {
let val13 = foo("val13")
}


What would be a good way to avoid all these ifs?

Edit: The strings are not actually called Val1 ... val13 (I used it as an example, might have been confusing, sorry).

Answer Source

In this situation, I'd probably use an array and a loop:

let vals = [];
for (let i = 1; i <= 13; ++i) {
    let name = "val" + i;
    if (foo(name)) {
        vals[i - 1] = foo(name);
    }
}

Note that if you assign to a later index without assigning to an earlier one, you end up with a sparse array. E.g.:

let a = [];
a[2] = "two";

...a has no entries for 0 or 1 at all. (Accessing them will give you the value undefined, though.)