During an interview for a front-end developer role, i was asked the question "what are closures?". And even though I've had about closures, I really don't know what they are and why they are important.
So, what are closures?
A closure is an object that stores the variables within the scope of an inner function when the function is created.
Below is an example to illustrate the concept of closures in action
Copy the code snippet above, save as index.html, What do you think would be logged by the console if we try to view the index.html file in the browser?. If your answer is "Result is 8",then you're completely right. In this code, we are returning the function exponent from the function base Open the browser console by pressing CTRL+SHIFT+J on windows and Linux, it's CMD + OPTION + J on Mac. Click on the sources tab, you should get something that looks like this
You should see something like the screenshot below.After adding the breakpoint, reload the index.html file.
After reloading the page, click on the step-into button(indicated with the small red circle above), then see the scope updated as we can see above. By clicking the step-into button, we're telling the debugger to continue execution by moving into the base function. Click on the step-into button one more time. to move to the return statement of the exponent function. The debugger should now be on the return statement of the exponent function and we can see the Closure in action. From the screenshot below, we can see the closure is an object with the property x holding the value 2.
Click on step-into two more times to get to the last line in the script tag and we can see the closure has been cleared. Closures appear to be very simple and straightforward but they can be a little bit hard to wrap your head around especially if you don't get the concept of scope.
If you enjoy this article, follow Moshood on twitter .