LoginSignup
22
20

More than 5 years have passed since last update.

javascriptでifやswitchを書きたくない時に

Posted at

ifやswitch これは便利です

※ifやswitchを否定しているわけではありません。

・例えば特定のtypeによって文字を表示したい場合

// if
var type = 'hoge';
function ifFunc(type){
    if (type === 'hoge'){
        console.log('hoge dayo');
    } else if (type === 'fuga'){
        console.log('fuga dayo');
    } else if (type === 'hoo'){
        console.log('hoo dayo');
    }
}

// switch case
function switchFunc(type){
    switch (type){
        case; 'hoge':
             console.log('hoge dayo');
             break;
        case; 'fugue':
             console.log('fuga dayo');
             break;
        case; 'hoo':
             console.log('hoo dayo');
             break;
    }
}


ifFunc(type);
switchFunc(type);

ifやswitchの罠

分岐する際全てをifやswitchを使うと処理を各パターンの時の処理が
ながくなって目的のものを探しにくくなったり、ネストが深くなったりして
可読性がさがることが個人的にありました。

funcオブジェクトを作成

じゃあ、どうしたかというとオブジェクトを作成して呼び出す形にしました

var funcObj = {
    hoge: function(){
        console.log('hoge dayo');
    },
    fuga: function(){
        console.log('fuga dayo');
    },
    hoo: function(){
        console.log('hoo dayo');
    }
}
var type = 'hoge';
var func = funcObj[type];
fun();

こうすることでifやcaseと書くことから解放されて
個人的に見やすく書けたのかなとおもっています。

ifやcaseを書かずに書いてみたい方は
試してみてください。

22
20
7

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
22
20