For a lot of folks who might have been programming for a while, this is straight-forward and easy to understand. To a beginner, this can be extremely confusing. It's a pattern so often used that, when I was first learning JavaScript, I thought foo , bar , bam , baz , bash were somehow special keywords like return and function .

When looking at code examples, the reader should be able to determine which parts of the example are essential, and which are non-essential like variable names, function names, arguments etc. In this post we'll use sandwiches, and the folks who make them, as examples for talking about JavaScript's closure . The ridiculously long variable and function names should make it easy to distinguish what parts of an example are part of the JavaScript language and syntax; and what parts are up to you as the developer to name.

Before we get started

We'll assume that you've already been writing a bit of JavaScript, that you understand functions and function declarations. Being familiar with scope) and Lexical Scope is necessary in order to understand the power of closures, so if you're not familiar with these concepts, take a little time to read up on them and come back.

What is a closure?

This is a question that often gets asked in technical interviews. Closures are not unique to JavaScript, but they are one of the things that makes JavaScript so powerful. "Closure" is a computer science term that defines how a function can maintain a record of the environment in which it was called. This means that a function can keep track of the arguments and variables it was initially called with, even when it's called outside of that scope. Put a slightly different way, the MDN Docs define closure as "the combination of a function and the lexical environment within which that function was declared." If that doesn't quite make sense, don't worry, we'll have it all figured out by the end of this post!

Where might you already be using Closures

All Javascript functions are closures. Functions have access to the variables defined within the function, along with variables defined in any enclosing scope(s), like the global scope. Other common places where closures occur are setTimeout , event/click handlers, and objects.

Why would you want to take advantage of closures?

As we stated above, you will use closure when defining click handlers, writing callbacks, or when you're using setTimeout or setInterval .