In ES5, writing such code has been considered as good practice:
(function () {
//some magic
})();
But in ES6 variables created with let
keyword are not attached to window
object.
So, is there any need now in writing our code in an IIFE, or it still has some purposes I haven't heard about?
In ES5, writing such code has been considered as good practice:
(function () {
//some magic
})();
But in ES6 variables created with let
keyword are not attached to window
object.
So, is there any need now in writing our code in an IIFE, or it still has some purposes I haven't heard about?
Share Improve this question edited May 23, 2016 at 19:53 Michał Perłakowski 92.5k30 gold badges163 silver badges186 bronze badges asked May 23, 2016 at 19:45 Vyacheslav PalamarVyacheslav Palamar 5071 gold badge3 silver badges12 bronze badges 5 |2 Answers
Reset to default 11If you're using modules, there's no need to use IIFE (that's how this "wrapper" is called), because all variables have scope limited to the module.
However, there still are some cases when you want to separate one part of the code from another, and then you can use IIFE.
Of course if you're using let
or const
, you can use a block statement instead of IIFE:
{
let something = 1;
const somethingElse = 2;
}
console.log(something); // ReferenceError: something is not defined
See related question on Programmers.SE: How far should encapsulation in JavaScript go?.
It is less of a problem now but I'd argue there's still a reason for that general idea.
Theoretically, it is possible for, say, some third-party library to write code like this following:
let count = 0;
function getCount() {
return count++;
}
Now, if you tried to create your own count
variable in the same scope, you'd get an error:
// 3rd-party
let count = 0;
function getCount() {
return count++;
}
// Your code
let count = 1;
However, you can make the code cleaner by using actual blocks instead of IIFEs.
// Still bad 3rd party
let count = 0;
function getCount() {
return count++;
}
// Your code
{
let count = 10;
console.log(count);
console.log(getCount());
console.log(count);
console.log(getCount());
}
In the future, you should be able to encapsulate your code in modules which will have their own scope and you won't need to wrap your code in an IIFE or a block.
let
keyword are not attached towindow
object" - but they are still global. So if you are writing scripts, you will need to put them in a block or an IIFE. – Bergi Commented May 23, 2016 at 20:05