Wednesday, February 11, 2015

Demystifying JavaScript Closures, Callbacks and IIFEs

We've already taken a close look at variable scope and hoisting, so today we’ll finish our exploration by examining three of the most important and heavily-used concepts in modern JavaScript development — closures, callbacks and IIFEs.


Closures


In JavaScript, a [closure](http://ift.tt/1fd07hh is any function that keeps reference to variables from its parent’s scope even after the parent has returned.


This means practically any function can be considered a closure, because, as we learned in the variable scope section from the first part of this tutorial, a function can refer to, or have access to –



  • any variables and parameters in its own function scope

  • any variables and parameters of outer (parent) functions

  • any variables from the global scope.


So, chances are you’ve already used closures without even knowing it. But our aim is not just to use them – it is to understand them. If we don’t understand how they work, we can’t use them properly. For that reason, we are going to split the above closure definition into three easy-to-comprehend points.


Point 1: You can refer to variables defined outside of the current function.


[code language="javascript"]function setLocation(city) { var country = "France"; function printLocation() { console.log("You are in " + city + ", " + country); } printLocation(); } setLocation ("Paris"); // output: You are in Paris, France [/code]

Try out the example in JS Bin


In this code example, the printLocation() function refers to the country variable and the city parameter of the enclosing (parent) setLocation() function. And the result is that, when setLocation() is called, printLocation() successfully uses the variables and parameters of the former to output “You are in Paris, France”.


Continue reading %Demystifying JavaScript Closures, Callbacks and IIFEs%




by Ivaylo Gerchev via SitePoint

No comments:

Post a Comment