What Is a Practical Use for a Closure in JavaScript

What is a practical use for a closure in JavaScript?

I've used closures to do things like:

a = (function () {
var privatefunction = function () {
alert('hello');
}

return {
publicfunction : function () {
privatefunction();
}
}
})();

As you can see there, a is now an object, with a method publicfunction ( a.publicfunction() ) which calls privatefunction, which only exists inside the closure. You can not call privatefunction directly (i.e. a.privatefunction() ), just publicfunction().

It's a minimal example, but maybe you can see uses to it? We used this to enforce public/private methods.

Specific real life application of closures in javascript

The main benefit to closures is you can "partially apply" a function using a closure, then pass the partially applied function around, instead of needing to pass the non-applied function, and any data you'll need to call it (very useful, in many scenarios).

Say you have a function f that will need in the future 2 pieces of data to operate. One approach is you could pass both pieces in as arguments when you call it. The problem with this approach is if the first piece of data is available immediately, and the second isn't, you'll have to pass it around with f so it's in scope when you want to call the function.

The other option is to give the available data to the function immediately. You can create a closure over the data, have the function reference the external data, then pass the function around by itself.

Option 2 is much simpler.

You can also use closures to implement static variables in functions in languages that don't natively support them. Clojure (the language) implements it's memoize function by having it return a modified version of the passed function that holds a reference to a map representing argument/return value pairs. Before the function is run, it first checks if the arguments already exist in the map. If they do, it returns the cached return value instead of recalculating it.

(Adapted from my answer to another question)

Good examples for using a Closure in Javascript

Currying variables

Since "closure" is just a way of saying that a function always retains its original variable scope, there are many ways you can take advantage of that.

Currying seems to be something that people like.


Creating curried value manipulators

Here I've created a function curry that will return a function that will be used to generate new functions that work with the original curried value.

function curry() {
var args = Array.prototype.slice.call(arguments);
return function(fn) {
return function() {
var args2 = Array.prototype.slice.call(arguments);
return fn.apply(this,args.concat(args2));
};
};
}

Creating a function that curries a string

So if I want to create functions to work with a string, I could curry the string...

var workWithName = curry("Bubba");

...and use the function returned to create new functions that work with the given string in various ways.


Create a function that puts the curried string in a sentence

Here I create a talkToName function that will incorporate the name into various sentences based on the arguments passed...

var talkToName = workWithName(function(curried_str, before, after) {
return before + curried_str + after;
});

So now I have a talkToName function that accepts 2 strings that wrap the curried string.

talkToName("Hello there ", ". How are you?"); // "Hello there Bubba. How are you?"
talkToName("", " is really super awesome."); // "Bubba is really super awesome."

Notice that I pass two arguments to the talkToName function, but the function given to workWithName accepts 3 arguments.

The first argument is passed by the function we created from workWithName(), and the two arguments we give to talkToName are added after the original curried argument.


Create a function increments the characters of the curried string

Here I create an entirely different function using the original workWithName function that will take the "Bubba" string, and return a string with the letters incremented by the given value...

var incrementName = workWithName(function(curried_str, n) {
var ret = '';
for(var i = 0; i < curried_str.length; i++) {
ret += String.fromCharCode(curried_str[i].charCodeAt() + n);
}
return ret;
});

So I pass my new incrementName function a number, and it increments the letters in the name, and returns the new string...

incrementName(3);  // "Exeed"
incrementName(8); // "J}jji"
incrementName(0); // "Bubba"

So you can see that we gave curry() a value, and it gave us back a function that can be used to create new functions that work with the original value.

Notice again that I pass one argument to the incrementName function, but the function given to workWithName accepts 2 arguments. The first argument is curried.


Other examples with numbers

Here's an example that creates a function generator that works with the numbers 3 and 5.

var workWith3And5 = curry(3, 5);

Create functions that do various things with the curried numbers

So using the workWith3And5 function, we make a new function that will accept a number argument, and return an Array of the sums of the curried numbers with the given number...

var addNTo3And5 = workWith3And5(function(x, y, n) {
return [3 + n, 5 + n];
});

addNTo3And5( 8 ); // [11, 13];
addNTo3And5( -4 ); // [-1, 1];

And another one using the same workWith3And5 function that curries the numbers 3 and 5 that creates a 3 x 5 Array of Arrays, where the nested Array is given some content...

var create3By5GridWithData = workWith3And5(function(x, y, data) {
var ret = []
for(var i = 0; i < x; i++) {
ret[i] = [];
for(var j = 0; j < y; j++) {
ret[i][j] = data;
}
}
return ret;
});

create3By5GridWithData( 'content' ); // [Array[5], Array[5], Array[5]]

How do JavaScript closures work?

A closure is a pairing of:

  1. A function and
  2. A reference to that function's outer scope (lexical environment)

A lexical environment is part of every execution context (stack frame) and is a map between identifiers (i.e. local variable names) and values.

Every function in JavaScript maintains a reference to its outer lexical environment. This reference is used to configure the execution context created when a function is invoked. This reference enables code inside the function to "see" variables declared outside the function, regardless of when and where the function is called.

If a function was called by a function, which in turn was called by another function, then a chain of references to outer lexical environments is created. This chain is called the scope chain.

In the following code, inner forms a closure with the lexical environment of the execution context created when foo is invoked, closing over variable secret:

function foo() {
const secret = Math.trunc(Math.random() * 100)
return function inner() {
console.log(`The secret number is ${secret}.`)
}
}
const f = foo() // `secret` is not directly accessible from outside `foo`
f() // The only way to retrieve `secret`, is to invoke `f`

What are the benefits of a closure, and when are they typically used?

They can be good for lots of things, for example, visibility (like private members in traditional OO).

var count = function(num) {

return function(add) {
add = add || 1;
num += add;
return num;
}

}

See it.

My count() can be seeded with a number. When I assign a variable to the return, I can call it with an optional number to add to the internal num (an argument originally, but still part of the scope of the returned function).

This is a pretty good overview.

See also on Stack Overflow

  • What is a practical use for a closure in JavaScript?
  • How does a javascript closure work ?
  • When actually is a closure created?
  • more...

JavaScript closure inside loops – simple practical example

Well, the problem is that the variable i, within each of your anonymous functions, is bound to the same variable outside of the function.

ES6 solution: let

ECMAScript 6 (ES6) introduces new let and const keywords that are scoped differently than var-based variables. For example, in a loop with a let-based index, each iteration through the loop will have a new variable i with loop scope, so your code would work as you expect. There are many resources, but I'd recommend 2ality's block-scoping post as a great source of information.

for (let i = 0; i < 3; i++) {
funcs[i] = function() {
console.log("My value: " + i);
};
}

Beware, though, that IE9-IE11 and Edge prior to Edge 14 support let but get the above wrong (they don't create a new i each time, so all the functions above would log 3 like they would if we used var). Edge 14 finally gets it right.



ES5.1 solution: forEach

With the relatively widespread availability of the Array.prototype.forEach function (in 2015), it's worth noting that in those situations involving iteration primarily over an array of values, .forEach() provides a clean, natural way to get a distinct closure for every iteration. That is, assuming you've got some sort of array containing values (DOM references, objects, whatever), and the problem arises of setting up callbacks specific to each element, you can do this:

var someArray = [ /* whatever */ ];
// ...
someArray.forEach(function(arrayElement) {
// ... code code code for this one element
someAsynchronousFunction(arrayElement, function() {
arrayElement.doSomething();
});
});

The idea is that each invocation of the callback function used with the .forEach loop will be its own closure. The parameter passed in to that handler is the array element specific to that particular step of the iteration. If it's used in an asynchronous callback, it won't collide with any of the other callbacks established at other steps of the iteration.

If you happen to be working in jQuery, the $.each() function gives you a similar capability.



Classic solution: Closures

What you want to do is bind the variable within each function to a separate, unchanging value outside of the function:

var funcs = [];

function createfunc(i) {
return function() {
console.log("My value: " + i);
};
}

for (var i = 0; i < 3; i++) {
funcs[i] = createfunc(i);
}

for (var j = 0; j < 3; j++) {
// and now let's run each one to see
funcs[j]();
}

Why do we have closures in JavaScript?

Closures add expressive power to the language. There are some patterns that can be implemented very easily because of closures. A few examples that come to mind include:

  • The Module Pattern - Example by Eric Miraglia
  • Memoization - Example by Oliver Steele
  • Currying - Example by Dustin Diaz

What is the exact use of closure?

In this example, there is no real difference in the output. However, let's make it even simpler:

function add(a) {  return function(b) {    return a+b;  }}

console.log(add(1)(2));


Related Topics



Leave a reply



Submit