I have a variable which I want to use in only one function. I can write my code like this:
var theAnswerToLife = 42
var multiplyIt = function(x) {
return ++theAnswerToLife * x
}
I have some other functions in that file, which don't use that variable. Therefore, in order to limit access to that variable to only the multiplyIt
function, I could wrap it in an IIFE:
var multiplyIt = (function() {
var theAnswerToLife = 42
return function(x) {
return ++theAnswerToLife * x
}
}())
Now that variable is available only to the inner function. Such encapsulation obviously makes sense when I have more variables, but is it worth it with only one variable? IIFE syntax is quite heavy, and in a more complex code I could end up having like three nested IIFEs.
How to keep balance between encapsulation and code readability? Where's the borderline?
My environment is Node.js, so a variable defined outside any function won't be global, but will be only available in the module scope.
push
should recreate the array every time it is called. Encapsulating that in a function call won't make a difference.push(1)
I get[1]
and then when I runpush(2)
I get[1, 2]
, not just[2]
.