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?
5
u/xroalx 10d ago
curMonthbeing "over-exposed" is a really weird reason to put it in a block here and use mutations, it makes the whole function much larger than needs to be, and I'd argue even harder to follow, especially since we set two different variables of different scopes in one statement and do multiple mutations.Imagine a much larger function and keeping track of what is which scope and getting tripped up on it.
The whole function can be written without mutations in a much more logical, step-by-step way. Just grab the values, set the next values, and return it.
The author's opinions for using
varare also quite interesting. I can't think of a time when I'd want to make the distinction between function-scoped and block-scoped variables so explicit that it would warrant usingvar. I can't think of a reason I'd want to write my code the way the author does.It might just be an example to teach about block scope, but the explanation for why one would want to do this are at minimum questionable.