Use of IIFE in ES6
In ES5 it is considered good practice to use IIFE to force a local scope in our code. EX:
(function(){
// some code
})();
In ES6 is this still necessary? Once the keyword let
has been introduced for variable declaration?
Thank you.
1 answers
When declaring variables with var
in JS, you had to create a new lexical scope so as 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 after, since 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 in ES6, with the introduction of let
and const
, which are block-scoped declarators, this is really no longer I need it. 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 IIFE, in ES6+ just create a block ({ ... }
).
let x = 1;
{
let x = 2;
}
console.log(x);
// => 1
As you may already know, all this is because:
-
var
is scoped by function -
let
andconst
are scoped by block