Understand Closures in JavaScript
Posted By : Vinay Tiwari | 27-Dec-2017
In this blog, we will understand closures in javascript. A closure is an inner function that has access to the outer function's variable in addition to its own variables and global variables. The inner function can access the outer function's variables across with the outer function's parameters. One can create a closure by adding a function in another function. The inner function cannot access the outer function’s arguments object, however, even though it can only access the outer function’s parameters. Let's create a function, this function is going to have two parameters firstNumber & secondNumber and inside this function let's create a variable let's name it returnValue. Let's initialize that with the string and inside this function I am going to have another function.
Now will define the code structure
function addNumbers (firstNumber, secondNumber){
var returnValue = "Result is : "
function add()
{
return returnValue + (firstNumber + secondNumber)
}
return add();
}
var result = addNumbers(10, 20);
console.log(result); // Result is : 30
Declaration:
First, we create a function its name it addNumbers(). This function is going to have two parameters firstNumber & secondNumber and inside this function let's create a variable let's name it returnValue. Let's initialize that with the string and inside this function I am going to have another function and let's name it to add(). And this function is going to return returnValue variable by concatenating that with the sum of firstNumber & secondNumber. Now noticed that we got a function inside another function. So, function add() is a inner function & function addNumbers() is a outer function. An inner function will have access to the outer function parameters and variables. So in this example add function() will have access to a returnValue variable to represent this outer function and its parameters firstNumber & secondNumber and then the outer function is going to call the inner function that is add().
Notice that the inner function cannot access the outer function’s arguments, however, even though it can only access the outer function’s parameters.
Cookies are important to the proper functioning of a site. To improve your experience, we use cookies to remember log-in details and provide secure log-in, collect statistics to optimize site functionality, and deliver content tailored to your interests. Click Agree and Proceed to accept cookies and go directly to the site or click on View Cookie Settings to see detailed descriptions of the types of cookies and choose whether to accept certain cookies while on the site.
About Author
Vinay Tiwari
Vinay is a bright UI developer, having knowledge of HTML, CSS, Bootstrap, Jquery and AngularJs. His hobbies are interacting with people, listening music etc.