Use of IIFE in ES6

Asked

Viewed 760 times

5

In ES5 it is considered a good practice to use IIFE to force a local scope in our code. EX:

(function(){
  // some code
})();

In ES6 this is still necessary? Once keyword has been introduced let for variable declaration?

Thank you.

  • It is no longer necessary if you use the module engine. Let itself does not isolate the overall scope.

1 answer

1

When declaring variables with var no JS, it was necessary to create a new lexical scope not to mess up the window (in most cases).

var abc = 1;

console.log(abc);
// => 1

console.log(window.abc);
// => 1

The simplest way was to create a function and call it right away, as Javascript functions create a new lexical scope. As you mentioned, they are the IIFE (Immediately Invoked Function Expressions):

(function(){
  var abc = 1;
})();

console.log(abc);
// => Uncaught ReferenceError: abc is not defined

But at ES6, with the introduction of let and const, which are declared scoped by block, this really is no longer accurate. For other uses, such as creating a namespace, or scoping variables, you still need to create a new lexical scope. But you don’t need to use the IIFE, in ES6+ just create one block ({ ... }).

let x = 1;

{
  let x = 2;
}

console.log(x);
// => 1

As you may already know, all this is due because:

  • var is cleared by function
  • let and const are drained by block

Browser other questions tagged

You are not signed in. Login or sign up in order to post.