Basically, you have two range checks in your code right now, and that's the biggest issue.
Here's the first check:
day = daysOfWeek[day - 1];
... which ends with undefined unless day has valid value (so that there's an element in daysOfWeek that corresponds to that value).
And here's the second check:
if (day > 7 || day < 1) { ... }
... which ends up doing wrong things because day variable gets a different value in that line of the first check. You can fix this, of course, by introducing another name...
const dayTitle = daysOfWeek[day - 1];
if (day > 7 || day < 1) { ... }
... but that means you're still checking the same condition twice. And it's never a good idea to repeat yourself.
So here's how it can be done:
function returnDay(day) {
return daysOfWeek[day - 1] || null;
}
... yep, that simple: the boundary range check now is done by JS, not you and your code. In other words, if day value cannot be used as a proper index for that dayOfWeek array, you'll just get undefined (which will be coalesced by || null to, well, null).
And yes, having null as kind of default value in this case seems weird to me.
daysOfWeekat indexday - 1is undefined? May you share an example where you call the function, along with an example ofdaysOfWeek?daysOfWeekto the question.day = daysOfWeek[day-1];You're overwritingday, so it's no longer going to be a number after this point. So the check on the line after this isn't going to work as you expect it to.daybefore checking whether the input is valid.