I'm reading an article about IIFEs but feel that the main value it brings is that it creates privacies for variables in the sense that in the below code, "i" can't be changed if placed in an IIFE. But what about the namespacing? How is there a difference between the two given they both contain their variables in the scope of "counter"?
var counter = {
i: 0,
increment: function () {i++;}
};
var counter = (function () {
var i = 0;
return {
increment: function () {i++;}
};
})();
There is no way to access a local variable from outside of the function that declared it, unless the function chooses to return a reference. Since Javascript only has function scope and no version provides a
namespaceblock, this is the only way to hide a variable from other code.With the other scopes introduced by ES6, you can use block scope or, ideally, module scope to simplify this: