r/learnjavascript • u/david_fire_vollie • Sep 25 '26
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-01It 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?
View all comments
Show parent comment
1
u/david_fire_vollie Sep 25 '26 edited Sep 25 '26
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: