Closures: Behind the Scenes!

Welcome!


Hi, Welcome! We will discuss a very interesting concept related to functions, “Closures”, what they are and how to use them. Let’s get started!



First of all, what is a Closure?


The concept might be a little bit abstract at first, so let’s jump to a concrete example:

What does a Closure look like?


Here you can see the general structure of a Closure:
  • We have an enclosing function (returnMultiplyFunction) with a nested function (multiplyBy).
  • The nested function uses a variable that is part of the enclosing function’s scope (in this case, multiplyBy uses x, the parameter passed to the outer function)
  • The inner function is returned by the enclosing function.
NOTE: A Nested function is a function defined inside another function.



You may ask, what happens when we call multiplyBy? We have two variables but we only pass in one argument, y. What value will x have? Let’s find out! : )

Ready? Set. Go!


Now let’s see a Closure in action:
  • When we call returnMultiplyFunction(5) we are executing the code that will return its nested function multiplyBy. But as we noticed in the diagram above, multiplyBy uses a variable x that is passed in as an argument to the enclosing function returnMultiplyFunction.
  • A “version” of the inner function will be returned. This “version” will be the function multiplyBy but with the variables of the enclosing scope replaced by their corresponding values (in this case x will no longer be a variable, it will be replaced by a value on the function returned).
This way we can create different versions of the function depending on our needs.
Let’s illustrate this concept with a more concrete example:
As you can see in the diagram above, if we need to create a function multiplyBy that multiplies its argument (in this case y) by 5, we need to pass in 5 as the argument to the outer function returnMultiplyFunction to replace x with the value 5.
  • This “version” of the function with x as 5 is returned and we assign it to a variable var1 for later use.
  • Then, to execute this “version” of multiplyBy, we call the function by using parentheses on the variable that stores the function returned var1(10).


Summary

Let’s recap with a brief summary: We pass 5 as the argument to returnMultiplyFunction, the outer function. This creates a “version” of the inner function that multiplies its argument by 5. When we call this new version, it multiplies 10, the argument passed during the function call by 5 and therefore we get 50.


Hope this helps!
If you have any questions, please do not hesitate to ask on the forums or right below this post, Community TAs and your classmates will be there to help you.
Estefania.

Comments

  1. This is good! Just out of interest, how did you create this blog? I think this is something eDX MIT should include in the syllabus, "Practical aspects of programming".

    ReplyDelete

Post a Comment