Wrapping an entire JS code block within {} in ES6

What’s the point of wrapping an entire code block within two curly braces? For example within .js file:

{    
const firstVar;

class firstClass {}

class secondClass {}    
}

Is this to create a blockscope and keep the global name space clean? Is it comparable to wrapping an entire javascript module within a self invoking function for example?

Take a look at this JS file for example;

https://github.com/codrops/PageFlipLayout/blob/master/js/demo.js

Answer

Yes, it is very similar to the old practice of creating an IIFE to isolate your variables from the global scope.

Since const and let are block scoped, as opposed to lexical (or function) scoped, you don’t need to create an entire function and call it. Just wrapping it in a block is enough.

{
  const foo = 42;
  console.log(foo); // 42
}
console.log(foo); // ReferenceError

It’s worth noting that this practice is still less used (and less powerful) than an IIFE, since an IIFE also protects you from leaking vars and function declarations, which a block would not. Although the common use-case today is to use a module, which would implicitly prevent leaking variables and objects into the global scope.

Only let, const and class are block-scoped.

Leave a Reply

Your email address will not be published. Required fields are marked *