node-style-guide icon indicating copy to clipboard operation
node-style-guide copied to clipboard

switch?

Open paulomcnally opened this issue 10 years ago • 2 comments

What is the best practices with switch?

switch (new Date().getDay()) {
    case 0:
        day = "Sunday";
        break;
    case 1:
        day = "Monday";
        break;
    case 2:
        day = "Tuesday";
        break;
    case 3:
        day = "Wednesday";
        break;
    case 4:
        day = "Thursday";
        break;
    case 5:
        day = "Friday";
        break;
    case 6:
        day = "Saturday";
        break;
}

paulomcnally avatar Dec 24 '14 16:12 paulomcnally

I would say try to avoid using switch. It is many times a smell of some kind of object hierarchy. In your example way clearer to use a plain data-structure that contains the day information:

var DAYS = ["Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday"];
var day = DAYS[new Date().getDay()];

I don't state that switch is always wrong, in some cases it is the best option, but it is a dangerous tool (you can forget breaks) and many times there is a way clearer and easier to read way.

EggDice avatar Dec 25 '14 00:12 EggDice

@EggDice, for the record, could you send a PR?

gergelyke avatar Dec 25 '14 07:12 gergelyke