JavaScript -> Closures

Introduction

A closure is the combination of a function and the lexical environment within which that function was declared.

In simple terms:

  • a closure is a function within a function if returned as function keeps the local variables of the returning function outside of its scope alive.
  • a closure is a stack frame which is allocated when a function starts its execution, and not freed after the function returns. (ref)
  • A closure is one way of supporting first-class functions; it is an expression that can reference variables within its scope (when it was first declared), be assigned to a variable, be passed as an argument to a function, or be returned as a function result. (ref)

Examples

Okay that was not really that much more easy to understand so let me show you some examples.

#1

What can we observe here? First of all the inner function definition theClosure gives it self away. The inner function definition within the function always have access to their containing 'outer' function.

That is why we can access the local variable name  from the 'outer' function ->returnLocalVariable within the 'inner' function -> theClosure. The stack frame allocated by the outer function does not get freed so that the inner function can access all variables within the same scope(stack frame).

For many programmer coming from C/C++ or similar languages this might look wrong. Why, because the lifetime of an local variable is bound by its (lexical)scope( stack frame). The scope of name ends when we return the inner function because usually the system would now deallocate the stack frame we allocated when entering the outer function.

So many people might think that this code will not work because name should not be accessible anymore if the user tries to call the returned inner function which itself tries to return the local variable of its outer function of the supposed deallocated stack frame.

But here lies the magic of the closures.  If you decide to define a new function within a function you automatically are declaring a closure.  If you then decide to return the closure, so that it can be called outside its defining function, you are telling the JavaScript environment to keep the scope of the defining function alive so it can access the variables defined there. The stack frame will not be freed!!!!

The result of the function above will be:

In other words: Closures are nested function and every nested function has access to scope above it, if required the scope will kept alive till nothing references it anymore.

#2

Let us look at another example. We want to have a function which add an constant factor to any number given but we want choose what value this factor has without supplying this “factor” all the time to the function.

We need a way to store the factor and be able to create many different instances of functions containing different factors. Let’s give the closure a try:

Through closures we gain the ability to create functions where we can parameterize  certain parts of the function without providing parameters. You could almost say it is some form of “meta-programming” even so that is kind of a strech. Notice we used an anonymous function which we immediately return.

#3

Let us create yet another example. I want to have some kind of sequence generator (simple one) where i can traverse up and down and look at the current value:

So what is happening here? Essential the same stuff as before. But we can observe something very interesting.

First of all apparently we can have more than one closure at a time AND access those closures we return by name. Which brings as to the next thing we can observe: We are able to bundle closures into objects and name those closures.

If we take an closer look at that very same  bundle, we notice that we do not bundle all closures but only a subset of them. What happens with the ones not contained in the object we return? They are inaccessible for the user! In other terms: they are private.

The Conclusion

Isn’t that awesome? I do think so, because it enables us to modulize our programs. There is even a pattern for it the so called JavaScript Module Pattern. Through this technique we are not forced anymore to infest our global namespace with our code and symbols but instead separate different namespaces via closures and make our code more reusable!

What have we observed so far:

  • If the function keyword is found within a Function, that inner function is a closure
  • Closures do not have to be returned, but can if wished
  • You can have more then one closure at a time within a Function
  • You can bundle closures into objects and name these closures in that object
  • You can hide closures by not returning them

 

 

Leave a Reply

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