Last Updated: December 26, 2018
·
1.733K
· brandturner

Eureka! I finally understand closures

Take this example JS code:

function makeAddFunction(amount) {
    function add(number) {
        return number + amount;
    }

    return add;
}

Now, I can do this:

addTwo = makeAddFunction(2);
addTwo(7);

The result will be 9. This is equivalent to makeAddFunction(2)(7). The addTwo variable can maintain it's state and wait until later to execute. The inner function retains access to the environment that existed at the point that it was defined. The variable number is not set until a function call on addTwo is made. If the argument for addTwo is generated dynamically and that variable is set well outside of the scope of the original function, I can still pass that variable through.

The inner function now has the flexibility to be made to do different things. This gives me the ability to create similar functions that give different results.

Also, this gives different functions access to the same variable name, creating a sort of namespace for js

5 Responses
Add your response

okay, so I understand the example you've given but I'm still not 100% clear about the what and why of closures. I feel like there are two aspects to my "mental fog" around this, and maybe you can help.

1) Definition of a closure : a function inside a function (?) that operates on the original function output(?), as kind of a secondary process, and in your example seems to accept its own arguments (? - I assume not always ?)
2) Can you illustrate a more "real world" use case ? explaining why one would choose to use a closure (?)

over 1 year ago ·

Okay, did some googling (I cannot recall the number of times I looked this up casually), I found the following, which - armed with your example (and maybe some more experience), made a lot more sense :

http://www.jibbering.com/faq/faq_notes/closures.html

A "closure" is an expression (typically a function) that can have free variables together with an environment that binds those variables (that "closes" the expression).

The simple explanation of a Closure is that ECMAScript allows inner functions; function definitions and function expressions that are inside the function bodes of other functions. And that those inner functions are allowed access to all of the local variables, parameters and declared inner functions within their outer function(s). A closure is formed when one of those inner functions is made accessible outside of the function in which it was contained, so that it may be executed after the outer function has returned. At which point it still has access to the local variables, parameters and inner function declarations of its outer function. Those local variables, parameter and function declarations (initially) have the values that they had when the outer function returned and may be interacted with by the inner function.

This stack overflow thread was super helpful.

http://stackoverflow.com/questions/1801957/what-exactly-does-closure-refer-to-in-javascript

over 1 year ago ·

Closure in JS can give you one (of many) awesome thing -> "private" functions/variables. Look at the scope of this in that example. If you don't return add function you can use only inside makeAddFunction.
Also look at this book and especially into module and revealing module pattern:
http://www.addyosmani.com/resources/essentialjsdesignpatterns/book/#revealingmodulepatternjavascript

over 1 year ago ·

Closures are really helpful. Now I'm not a javascript developer, so instead I present psuedo-code.

Consider you wanted a function, that you could pass in some accumulator object, whose value would be taken and applied to each iteration of the block evaluated against. So for instance:

[1,2,3,4,5].reduce(1, function(a, idx, b) { /* a is the accumulator, initially 1, b is the current element while iterating the list */ return a * b; });

This produces a single result when it returns: 120 (astute readers will realize this is an implementation of factorial).

It could be implemented like this:

function reduce(acc, fn) {
    for(var i = 0; i < this.length; i++) {
        acc = fn(acc, i, this[i]);
    }
    return acc;
}

Now let's say we wanted to apply a transformation to each object in the list, in this case, let's say squaring numbers to keep it simple, we could implement a function in terms of reduce above

function map(fn) {
return this.reduce(new Array(this.length), function(acc, idx, elem) {
acc[idx] = fn(elem);
return acc;
}
}

This will let you calculate the square numbers from a sequence of numbers 1..n where in this example I'll define n as being equal to 5, like so:

[1,2,3,4,5].map(function(elem) { return elem * 2; })

The output of which will be this:

[2,4,6,8,10]

It doesn't take much to realize how these simple primitive operations I've defined above can be used on all sorts of data types to yield some wonderfully elegant and flexible code.

Full disclosure, I have not proven the above code correct in any language, but it should be "close enough" in many languages to be useful. Again, I'm not a Javascript programmer.

over 1 year ago ·

I strongly recommend taking this course:
https://www.coursera.org/course/proglang

After you implement your own closures in Racket you will finally understand them. Like really understand.

over 1 year ago ·