The code works but has some issues.
return firstMonday.setDate(firstMonday.getDate() + 7 * (weekNo - 1));
returns a time value (the return from setDate). To return a Date, it should be two separate statements:
firstMonday.setDate(firstMonday.getDate() + 7 * (weekNo - 1));
return firstMonday;
Also, looping to find the first Monday is inefficient. It can be calculated from the initial value of firstMonday. Checking for week 53 can also be simplified and the input week number should be tested to ensure it's from 1 to 53.
Lastly, the first couple of days of January may be in the last week of the previous year, so in week 53 getting week 53 with the default year may return the start of week 53 of the wrong year (or undefined, see below). It would be better if the function took two arguments: weekNo and year, where year defaults to the current year and weekNo to the current week.
/* Return date for Monday of supplied ISO week number
* @param {number|string} weekNo - integer from 1 to 53
* @returns {Date} Monday of chosen week or
* undefined if input is invalid
*/
function getFirstMondayOfWeek(weekNo) {
let year = new Date().getFullYear();
// Test weekNo is an integer in range 1 to 53
if (Number.isInteger(+weekNo) && weekNo > 0 && weekNo < 54) {
// Get to Monday of first ISO week of year
var firstMonday = new Date(year, 0, 4);
firstMonday.setDate(firstMonday.getDate() + (1 - firstMonday.getDay()));
// Add required weeks
firstMonday.setDate(firstMonday.getDate() + 7 * (weekNo - 1));
// Check still in correct year (e.g. weekNo 53 in year of 52 weeks)
if (firstMonday.getFullYear() <= year) {
return firstMonday;
}
}
// If not an integer or out of range, return undefined
return;
}
// Test weeks, there is no week 53 in 2021
[0, '1', 34, 52, 53, 54, 'foo'].forEach(weekNo => {
let date = getFirstMondayOfWeek(weekNo);
console.log(`Week ${weekNo}: ${date? date.toDateString() : date}`);
});
Where an invalid week number is supplied you have a choice of throwing an error, returning undefined or returning an invalid Date:
return new Date(NaN);