Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

like image 945
kshatriiya Avatar asked Dec 28 '25 19:12

kshatriiya


1 Answers

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.

like image 131
Madara's Ghost Avatar answered Dec 31 '25 07:12

Madara's Ghost



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!