To get started, I’d like for you to take a look at this function.
Here we have a function called sayInt, which takes in an integer and returns a function that returns a variable called number which is bound to our i argument in sayInt. Wow that seemed like a mouthful! Let’s break this down line by line to get ourselves acquainted with the terminology used in this post.
Line 1: This is the statement which defines our function.
Line 3: This return function is our closure because the function being returned is calling on a variable that’s outside of its lexical scope. The variable number is a local variable to the function sayInt, but it’s still accessible in the return function because of how closure works.
With closure, you can call on an outer function’s variables inside an inner function.
Line 6/7: Here we are setting our next two bindings. We’re binding int1 and int2 to the invocation of the function sayInt, but with varying arguments for what i will represent.
Line 9/10: Here is what we would like to print. The console.logs on 9 and 10 will print the number provided as the arguments in lines 6 and 7. Here we need to invoke our variables because otherwise we would print out our inner function, ( ) => number, instead of the result of our inner function. If we don’t invoke this function, we won’t have closure to our closure!
When we run this function we will receive a print out of 1 and 2.
To visualize what lexical scope is and how it relates to closure, imagine you’re on an airplane about to be given in-flight beverages. You can see the cart of drinks available to you, but are only given access to them whenever you ask the flight attendant.
Think of the plane as our outer function, the drinks as our variables, and your request for a beverage as our inner function. Being on the plane, or in our outer function, gives us access to our drink variables. We call on one of these variables when we invoke our inner function (asking for a drink).
I hope that this gave you a little closure on your adventure learning closure. All that’s left to do now is sit back, relax, and enjoy the flight.