DEV Community

Discussion on: If (all) else is complicated, switch to switch?

Collapse
 
andrewbridge profile image
Andrew Bridge

I agree with your initial point, but not necessarily that switches are the answer.

In your example, I'd probably do something like:

const states = {
    foo: stateA,
    bar: stateB
};

const f = (value) => {
    if (!(value in states)) {
        throw new Error(`No state for ${value}`);
    }
    return states[value]();
}
Enter fullscreen mode Exit fullscreen mode

...or more generically assuming things weren't as 1-to-1...

const f = (value) => {
    if (value === 'foo') {
        return stateA();
    }
    if (value === 'bar') {
        return stateB();
    }
    throw new Error(`No state for ${value}`);
}
Enter fullscreen mode Exit fullscreen mode

The second is probably the easiest to understand out of all of them (including the switch imo) so I'd probably lean towards that, but in every case, undefined behaviours are caught appropriately.