Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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

like image 904
Staxxx6 Avatar asked Jan 24 '26 22:01

Staxxx6


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

like image 130
Quentin Avatar answered Jan 27 '26 11:01

Quentin