DEV Community

Discussion on: How to write a great switch statement in JavaScript

Collapse
 
leandroandrade profile image
Leandro Andrade

Nice pont of view. Another way that I do the same thing but not use switch is:

function processByType({ type, ...args }) {
    const fns = {
        CONST_VALUE_A: processArgsA,
        CONST_VALUE_B: processArgsB,
        CONST_VALUE_C: processArgsC
    };

    const fn = fns[type];
    if(!fn) throw new Error(`unknown type ${type}`);
    return fn(args);
}
Collapse
 
harryadel profile image
Harry Adel

Was just about to point the same thing. I feel switch statements are obsolete when you got bracket notation that allows you to do the same thing in a much simpler way.