Friday, July 29, 2016

JavaScript Closures - Simple examples you can use to demonstrate them

I hope you will not have to keep Googling them after this post. But, you should continue to dig in to them. They are useful, powerful and you will get asked about them in every single JavaScript interview. I do JavaScript tech screenings every day and I ask the candidate to "briefly describe a closure". You should be able to do that and demonstrate it on a whiteboard or in a live coding exercise.

What is a Closure?
"A function that captures the external bindings (i.e., not its own arguments) contained in the scope in which it was defined for later use (even after that scope has completed)."
-Fogus, Michael (2013-06-01). Functional JavaScript: Introducing Functional Programming with Underscore.js. O'Reilly Media.   

I could not have said it better so I won't try to. Basically, the variables survive the return of the outer function. 

So what? Why would I use one myself?

You can use the captured variables as private data because the only way to get at them is if the closure returns the value of it

It is also a great way to offer abstraction. You use closures all the time and don't realize it.

How?

localVarOfOuterFunc is local before outerFunction returns. Take a look at Scope in dev tools.

localVarOfOuterFunc hangs on after outerFunction returns and is available to innerFunction. Take a look at Scope in dev tools again and observe the Closure


Practice by actually typing in my example. I know I'm a jerk for not putting code that can just be copied and pasted but if you already knew how to demo this, you wouldn't still be reading this and so typing it out will help you remember it. Well, it should! It helps me. Start with my code, build some more functions outward and inward and step through the code. Watch the Scope in the debugger. The fact that you know that Closure shows up under Scope in Chrome Dev Tools already puts you ahead of most candidates.

OK, go back to Googling them now.

No comments:

Post a Comment