Block-Scoped Functions in JavaScript

Kavindu Wijesuriya | Thu Aug 12 2021

In ES6 when you declare a function inside a block, that function is only visible within that block scope.

Consider:

block scoped functions behavior in JavaScript

As you can see the *doStuff()* function is declared inside the { ... } block. If we reference the *doStuff()* function inside the block, it works as expected. When we try to reference it outside of the block, we get a reference error as it is not available. Also notice that the function *doStuff()* is hoisted to the top of the block, meaning that even if we referenced it earlier in the code, it will work correctly.

But as a practice I like to declare my function early before they are referenced to avoid any confusion. Just because a language feature is there we don't have to sacrifice readability.

built with from scratch by Kavindu Wijesuriya