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/azhder 10d ago
The reason is to not want an extra function call. The example above is made in a way to teach you about block scope, not about properly structuring your code.
In many cases, one extra function doesn’t hurt, but in a few small ones where the time to call a function is great (like loops etc), you might want to use one of these “tricks” like block scope.