Anonymous functions

Last Updated on: September 15, 2022

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.


Get notified of new posts:


Similar Posts

Leave a Reply

Your email address will not be published. Required fields are marked *