JavaScript is a function-oriented language that gives a lot of freedom to the user. You can create a function dynamically, copy it to another variable or pass as an argument to another function and call from a different place later. Closures in JavaScript are created every time a function is created, at function creation time. In this article, we will understand closures in the following sequence:
Introduction to Closures in JavaScript
A closure is a combination of a function bundled together with references to its surrounding state i.e. the lexical environment. In other words, a closure provides you access from an inner function to an outer function’s scope.
Most of the Developers use closures in JavaScript consciously or unconsciously. It provides better control over the code when using them. Also, it is the most frequently asked question during any JavaScript interview.
Example:
function foo() { var x = 10; function inner(){ return x; } return inner; } var get_func_inner = foo(); console.log(get_func_inner()); console.log(get_func_inner()); console.log(get_func_inner());
Output:
10
10
10
Here, you can access the variable x which is defined in function foo() through function inner() as the later preserves the scope chain of enclosing function at the time of execution of enclosing function. Thus, the inner function knows the value of x through it’s scope chain. This is how you can use closures in JavaScript.
Take your design skills to the next level with our UI Design Course.
Practical Closures
Closures allow you to associate the lexical environment with a function that operates on that data. This has obvious parallels to object-oriented programming, where objects allow us to associate the object’s properties with one or more methods.
Consequently, you can use a closure anywhere that you might normally use an object with only a single method.
Example:
function makeSizer(size) { return function() { document.body.style.fontSize = size + 'px'; }; } var size12 = makeSizer(12); var size14 = makeSizer(14); var size16 = makeSizer(16);
The above example is generally attached as a callback: a single function which is executed in response to the event.
Scope Chain
Closures in JavaScript have three scopes such as:
- Local Scope
- Outer Functions Scope
- Global Scope
A common mistake is not realizing that, in the case where the outer function is itself a nested function, access to the outer function’s scope includes the enclosing scope of the outer function, effectively creating a chain of function scopes.
// global scope var x = 10; function sum(a){ return function(b){ return function(c){ // outer functions scope return function(d){ // local scope return a + b + c + d + x; } } } } console.log(sum(1)(2)(3)(4)); // log 20
It can also be written without anonymous functions:
// global scope var x = 10; function sum(a){ return function sum2(b){ return function sum3(c){ // outer functions scope return function sum4(d){ // local scope return a + b + c + d + x; } } } } var s = sum(1); var s1 = s(2); var s2 = s1(3); var s3 = s2(4); console.log(s3) //log 20
In the above example, there is a series of nested functions all of which have access to the outer scope of a function.Thus, you can say that closures have access to all outer function scopes within which they were declared. Check out this Web developer course online to learn more about Javascript functions.
Closure Within a Loop
You can use closures in JavaScript to store an anonymous function at every index of an array. Let’s take an example and see how closures are used within a loop.
Example:
function outer() { var arr = []; var i; for (i = 0; i < 3; i++) { // storing anonymus function arr[i] = function () { return i; } } // returning the array. return arr; } var get_arr = outer(); console.log(get_arr[0]()); console.log(get_arr[1]()); console.log(get_arr[2]());
Output:
3
3
3
3
With this, we have come to the end of our article. I hope you understood how closures in JavaScript works and how they are used to get a better control of the code.
Now that you know about Closures in JavaScript, check out the Web Development Certification Training by Edureka. Web Development Certification Training will help you Learn how to create impressive websites using HTML5, CSS3, Twitter Bootstrap 3, jQuery and Google APIs and deploy it to Amazon Simple Storage Service(S3).
Check out the Angular certification training course by Edureka, a trusted online learning company with a network of more than 250,000 satisfied learners spread across the globe. Angular is a JavaScript framework that is used to create scalable, enterprise, and performance client-side web applications. With Angular framework adoption being high, performance management of the application is community-driven indirectly driving better job opportunities.
If you want to get trained in React and wish to develop interesting UI’s on your own, then check out the React JS Online Course by Edureka, a trusted online learning company with a network of more than 250,000 satisfied learners spread across the globe.
Got a question for us? Please mention it in the comments section of “Closures in JavaScript” and we will get back to you.