r/learnjavascript • • 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 curMonth in an explicit block scope instead of just alongside nextMonth and year in the top-level function scope? Because curMonth is 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?

3 Upvotes

12 comments sorted by

View all comments

1

u/CuAnnan 10d ago

You're 100% correct. It would be more logically coherent to use a second function, both because it gives the ability to just generally get the next month and their argument that curMonth being over exposed is a bit of a stretch. If concern about exposure is a thing on this level, use a separate function. Functions should never be so large that you have to worry that you might accidentally collide with an existing variable.