Function Object - in JavaScript

In JavaScript

In JavaScript, functions are first class objects. JavaScript also supports closures.

Compare the following with the subsequent Python example.

function Accumulator(start) { var current = start; return function (x) { return current += x; }; }

An example of this in use:

var a = Accumulator(4); var x = a(5); // x has value 9 x = a(2); // x has value 11 var b = Accumulator(42); x = b(7); // x has value 49 (current = 42 in closure b) x = a(7); // x has value 18 (current = 11 in closure a)

Read more about this topic:  Function Object