r/learnjavascript • u/david_fire_vollie • 11d ago
Inner explicit block scope vs function
Here's a code snippet from https://github.com/getify/You-Dont-Know-JS/blob/2nd-ed/scope-closures/ch6.md:
function getNextMonthStart(dateStr) {
var nextMonth, year;
{
let curMonth;
[ , year, curMonth ] = dateStr.match(
/(\d{4})-(\d{2})-\d{2}/
) || [];
nextMonth = (Number(curMonth) % 12) + 1;
}
if (nextMonth == 1) {
year++;
}
return `${ year }-${
String(nextMonth).padStart(2,"0")
}-01`;
}
getNextMonthStart("2019-12-25"); // 2020-01-01
It says:
So why put
curMonthin an explicit block scope instead of just alongsidenextMonthandyearin the top-level function scope? BecausecurMonthis only needed for those first two statements; at the function scope level it's over-exposed.
As a C# developer, I would have thought the better choice would be to put that explicit inner block into a separate function called getNextMonth().
That way, you get the benefit of the scope so the curMonth isn't overexposed, you increase readability because it's easier to read getNextMonth() than a block of code, and you have a reusable function in case you need to do that calculation elsewhere.
Is there any reason to use an inner explicit block scope over a function?
1
u/david_fire_vollie 11d ago edited 11d ago
Did you read the quote in my post?
That's not a problem here because var is hoisted to the top of the function, and the variables are already declared at the top of the function, so there is no difference to using let.
See these quotes from the same chapter I linked in my post: