JavaScript and JQuery Essentials Trainin... (56 Blogs) Become a Certified Professional
AWS Global Infrastructure

Front End Web Development

Topics Covered
  • AngularJS (29 Blogs)
  • jQuery UI Development (2 Blogs)
  • The Complete WebDeveloper (38 Blogs)
  • ReactJS (7 Blogs)
SEE MORE

MI-new-launch

myMock Interview Service for Real Tech Jobs

myMock-widget-banner-bg

What are Closures in JavaScript & How Do They Work?

Last updated on Nov 27,2019 87 Views
A Data Science Enthusiast with in-hand skills in programming languages such as... A Data Science Enthusiast with in-hand skills in programming languages such as Java & Python.

MI-new-launch

myMock Interview Service for Real Tech Jobs

myMock-mobile-banner-bg

myMock Interview Service for Real Tech Jobs

  • Mock interview in latest tech domains i.e JAVA, AI, DEVOPS,etc
  • Get interviewed by leading tech experts
  • Real time assessment report and video recording

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.

coder - closures in javascript - edureka

 

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.

 

 

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.

 

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). 

Got a question for us? Please mention it in the comments section of “Closures in JavaScript” and we will get back to you.

Comments
0 Comments

Browse Categories

webinar REGISTER FOR FREE WEBINAR
REGISTER NOW
webinar_success Thank you for registering Join Edureka Meetup community for 100+ Free Webinars each month JOIN MEETUP GROUP

Subscribe to our Newsletter, and get personalized recommendations.