Is there any difference between using IIFY(Immediately-Invoked Function Expression) and {...}

Viewed 819
(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?

1 Answers

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).

Related