JavaScript allows the use of anonymous functions with full closures.

Functions are objects, and you can pass them as arguments like any other object.

The scope of a function includes all the names in the scope where it was declared. As you declare functions at run time and local variables can remain after the function returns, there are a number of closure options for coders.

Take this function, for example:

var range = function (begin, end, jump) {
  return function () {
    var at = begin;
    begin += jump;
    if (at < end) return at;
    else throw new Error ();

var next = range(0, 10, 2); /* range returns a function */

When you call next for the first time, it will return 0 and subsequently, it will return 2, 4, 6, and 8. After that will throw an error.

The local variables defined in range remain in memory until the next no longer exists.

The function returns an anonymous function that is a closure and both the function code and the reference to the scope of the function was declared.

When the function returns, it holds the “function allocation record” range in memory and so the value of begin persists to the next time that you call next.


Leave a Reply

Your email address will not be published.

More Posts

How to use PHP Type Declarations

PHP has developed into a more strictly typed language in recent years. Type Declarations help with that and are a fairly new addition to PHP,


If you have come to JavaScript from a background in Java or C, then you will like the variation on the for loop. It is

Context Object Manipulation

One of the key concepts of JavaScript is the keyword this, which signifies the JavaScript context object. If you write an inner function, you can access

Polymorphic Functions

It is possible to define multiple functions with the same name in JavaScript, and the last one of those that you define will be the