What if we could return a function expression that in-turn returns the values
array? Variables declared in a function are available to any code within the function, including self-invoking functions.
By using a self-invoking function, our dilemma is solved.
var ValueAccumulator = function() { var values = []; var accumulate = function(obj) { if (obj) { values.push(obj.value); return values; } else { return values; } }; return accumulate; }; //This allows us to do this: var accumulator = ValueAccumulator(); accumulator(obj1); accumulator(obj2); console.log(accumulator()); // Output: [obj1.value, obj2.value]
It's all about variable scoping. The values
variable is available to the inner accumulate()
function, even when code outside the scope calls the functions. This is called a closure.
Closures in JavaScript are functions that have access to the parent scope, even when the parent function has closed.
Closures are a feature of all functional languages. Traditional imperative languages do not allow them.