function getMonthName(monthNumber) {
const date = new Date();
date.setMonth(monthNumber - 1);
return date.toLocaleString([], { month: 'long' });
}
You must log in or register to comment.
You want to create the date “31st February”, but it’s JavaScript that’s cursed?
Write a less side-effecty function.
function getMonthName(monthNumber) { const date = new Date(2023, monthNumber - 1, 1); return date.toLocaleString([], { month: 'long' }); }
The point is that this scenario exists in Js in the first place. It’s a completely unnecessary rake left around for people to step on. Also, the function isn’t side effecty since it doesn’t make implicit references outside its scope. The fact that the date is mutable is an internal concern there. You could just as easily do
function getMonthName(monthNumber) { const date = new Date(); date.setDate(1); date.setMonth(monthNumber - 1); return date.toLocaleString([], { month: 'long' }); }
The problem here isn’t with side effects, but with having to know that you want to set your date to first day to get the next month reliably.