I’m reading this article
and there is a paragraph:
If you ever find yourself needing to explicitly scope a variable
inside a function you can use an anonymous function to do this. You
can actually create an anonymous function and then execute it straight
away and all the variables inside will be scoped to the anonymous
function:
(function() {
var myProperty = "hello world";
alert(myProperty);
})();
alert(typeof(myProperty)); // undefined
I met with this already but still need some clarification why should I need to explicitly scope a variable inside a function when variables are implicitly scoped inside a function in Javascript.
Could you explain the purpose of this?
thank you
When generating functions inside other functions and accessing variables up the scope chain through closure scope it may be useful to “explicitly scope” a variable inside the outer function.
Although this is an anti pattern. The correct solution would be
Since generating functions in a loop is inefficient and bad practice.
There are no real use cases of “explicitly scoping” variables that can’t be avoided by not creating functions inside other functions.