3
(function() {
  let val = 10;
  console.log(val); // 10
})() // executed immediately
console.log(val); // val is not defined

VS

{
    let val = 10;
    console.log(val); //10 
} // executed immediately
console.log(val) // val is not defined

Both code snippets seem to have the same effect. Can these two approaches be used interchangeably? Am i missing something?

Staxxx6
  • 95
  • 5
  • Block works only if you use `const` or `let`. `var` would scope itself to the nearest function (or global, if none exists). – Joseph Jun 28 '19 at 16:52

1 Answers1

3

Using a block and let will have the same effect, but be more efficient than the IIFE in this case.

The IIFE pattern predates let being added to the JavaScript language so it is more common (and supported in IE10 and earlier).

Quentin
  • 914,110
  • 126
  • 1,211
  • 1,335