In JS, functions are not just functions. They are also closures. What that means is that the function body has access to variables that are defined outside the function body.

Take this example.

Screen Shot 2017-10-13 at 5.20.06 AM.png

Here we are able to execute the variable var me, defined outside the function scope of the function, because JS functions are closures.

Other languages like Java, C#, and Objective-C don’t work like that. Normally you need to define the variable in the same scope of the function or method using it. Or by passing it in. But not in JS. Here functions (or closures) have access to variables define elsewhere.

So why are closures useful? Let’s look at this example.

Screen Shot 2017-10-13 at 5.26.54 AM.png

This asynchronous ajax method callback, will have access to requestId, even though it will be called asynchronously sometime in the future.

This is a good use of closures. What you want to start a task, and set some variables up for the future. This makes the code easier to read.

 

 

 

 

 

 

 

 

 

 

Advertisements