Why does everyone do such a terrible job of explaining JS Closures?

While I was preparing for an interview with Hack Reactor I received an email that listed several concepts that I should be comfortable with before interviewing. Some of the topics listed included: callback functions, higher order-functions, and how and when to use anonymous functions. Another topic that was given to me as suggested reading material was an article on Javascript Closures. Because of my inexperience I assumed that the concept of closures was something very complicated that only advanced engineers would understand. It didn’t help that each time I googled for help I consistently came across explanations of closure that would contradict each other.

 Here is the simplest explanation of closure that I can manage:

A function’s scope remains intact even if it is called after its parent function and scope have closed.

Here’s an example:

var foo = function(){
  var x = "Hello World!";  
  return function() {  
    alert(x);    
  }  
};

var bar = foo();

bar(); //alerts "Hello World"

The important thing to note about the above function is that the function “foo” has finished executing. The function foo finishes executing and returns an anonymous function. Despite the fact that foo is finished, the anonymous function being returned still retains access to the variable “x”. This means that you have greater flexibility with how you write your functions. You don’t have to worry about any of your functions losing access to variables over the course of your program. Your functions will behave the way that they appear at the time of writing.

 
104
Kudos
 
104
Kudos

Now read this

Closure and For Loops

Note: If you don’t understand Javascript closures then I recommend you first check out this blog post. When I was interviewing for a job in San Francisco I was asked to fix the following code: for (var i = 0; i < 5; i++) {... Continue →