3

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

kshatriiya
  • 209
  • 4
  • 12
  • Possible duplicate of [JavaScript curly braces with no function or json](https://stackoverflow.com/questions/18130025/javascript-curly-braces-with-no-function-or-json) – markmoxx Dec 04 '18 at 12:55
  • related: [Will const and let make the IIFE pattern unnecessary?](https://stackoverflow.com/q/33534485/1048572) – Bergi Dec 04 '18 at 14:01

1 Answers1

5

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.

Madara's Ghost
  • 172,118
  • 50
  • 264
  • 308