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

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


Define an array, then get by index.

var months = ['January', 'February', ...];var month = months[mm - 1] || '';


what about not to use array at all :)

var objDate = new Date("10/11/2009"),    locale = "en-us",    month = objDate.toLocaleString(locale, { month: "long" });console.log(month);// or if you want the shorter date: (also possible to use "narrow" for "O"console.log(objDate.toLocaleString(locale, { month: "short" }));

as per this answer Get month name from Date from David Storey


Try this:

var months = {'1': 'January', '2': 'February'}; //etcvar month = months[mm];

Note that mm can be an integer or a string and it will still work.

If you want non-existing keys to result in empty string '' (instead of undefined), then add this line:

month = (month == undefined) ? '' : month;

JSFiddle.