How to shorten switch case block converting a number to a month name?

Leon Gaban picture Leon Gaban · Apr 23, 2015 · Viewed 8.3k times · Source

Is there a way to write this on fewer lines, but still easily readable?

var month = '';

switch(mm) {
    case '1':
        month = 'January';
        break;
    case '2':
        month = 'February';
        break;
    case '3':
        month = 'March';
        break;
    case '4':
        month = 'April';
        break;
    case '5':
        month = 'May';
        break;
    case '6':
        month = 'June';
        break;
    case '7':
        month = 'July';
        break;
    case '8':
        month = 'August';
        break;
    case '9':
        month = 'September';
        break;
    case '10':
        month = 'October';
        break;
    case '11':
        month = 'November';
        break;
    case '12':
        month = 'December';
        break;
}

Answer

xdazz picture xdazz · Apr 23, 2015

Define an array, then get by index.

var months = ['January', 'February', ...];

var month = months[mm - 1] || '';