The Story of Closure

Brad Hankee
Code a la Carte
Published in
1 min readAug 7, 2017

So I have been going back and learning the fundamentals one at a time in deeper context to be able to have a deeper understanding. One of the mystery topics that seem to get a lot of ‘ah’ and ‘um’s from new developers is on Closure in JavaScript.

For a definition it’s hard to beat Kyle Simpson’s that states:
Closure is when a function “remembers” it’s lexical scope even when the function is executed outside the lexical scope.

So what does this mean exactly? A good way to think of it it to start with using declared variables in certain scopes. If you have a function that has a return function passing a local variable normally that variable is limited in the scope. However when that function is used somewhere else it still has access to that variable because of…. CLOSURE!

A real world example involving AJAX would look something like:


function sendRequest() {
var id = ‘001’,$.ajax({url:”/about”,success: function(respond){alert(“show id: ” + id)}})}

So here if you run the function sendRequest in another part of the program the return function still has access to the variable “id”. This makes sense when you think about it in terms of lexical scope and being able to look upwards for variables.

A good way to think about this action in is to say that the return function “closes over” variable X. In my mind just by stating this shows how it wraps up the variable for use in another location.

follow my stuff at Twitter

— Brad

--

--

Brad Hankee
Code a la Carte

Full stack developer / foodie that writes about daily learnings.