In this article we will talk about functions in JavaScript , how functions invocation works and Closures.
What is function
A function is a set of statements that take inputs, do some specific calculations, and produces output. Basically, a function is a set of statements that performs some tasks or does some computations and then return the result to the user.
What is the need of a function
If we want to do some calculations. Let's say that if we want to add two numbers
var input1=10;
var input2=20;
var sum=input1+input2;
console.log(sum);
output
30
From the above code we calculate the sum of two numbers. But if we want to add again two numbers then we have to write the same code again and again and by writing same code again and again it basically increases our code length or increases the complexity also. To avoid this we can use functions.
With the help of functions we can write the code at once and use it many a times we want.
Syntax of writing the function
function function-name
(){
// statements
}
We can write the above code by using functions also.
function add(a,b){
var add= a+b;
console.log(add);
}
add(2,2);
Output
4
From the above code we can use it as many times as we want .
How the function execution works in JavaScript
Lets write a code:
var a=100;
first();
second();
console.log(a);
function first{
var a=10;
console.log(a);
}
function second(){
var a=20;
console.log(a);
}
Output
10
20
100
Let's understand what happen behind this .
As we know a global execution context is created and it will put inside the call stack and inside the global execution context we have two blocks first is a memory execution other one is code execution.
As we know JavaScript assign memory to variables and functions during the 1st phase it gives undefined to variables and in case of functions it will take the whole function. So from the above code when it calls first() so one more execution context is created for that function. Now same things happen for this also like during the 1st phase JavaScript allocate memory to variables and functions and then code execution phase started now it finds the value of a in local memory and prints the value of a
as 10. After doing all this execution context is deleted .
Now it move forward and again see a function call now again it will do all the things for second()
describe above and prints the value of a
as 20. After that the execution context is deleted and again move forward to the next line.
In the end it will print the value of a
as 100 it will print the output to the console.
What is Closure
Before understanding closure do you know about lexical scope. If you know then ok if you don't then checkout my article on lexical scope.
Now let's understand what is closure .
Closure is a combination of function bundled together along with its lexical environment.
Didn't understand the above line don't worry .
Lets understand with the help of an example
function outer(){
var a=10;
function inner(){
console.log(a);
}
inner();
}
outer();
As we know the above code gives the output as 10 why because as we studied previously if a is not present in their local scope then it goes to the parent now read the above definition again.
In this case we can say inner()
is a function which is bundled or we can say combine together with their lexical environment of their parent.
In other words, a closure gives you access to an outer function's scope from an inner function. In JavaScript, closures are created every time a function is created, at function creation time.
Now let's see what happens when we return the value of inner function let's understand.
function outer(){
var a=10;
function inner(){
console.log(a);
}
return inner;
}
var store=outer();
console.log(store);
Output
function inner(){
console.log(a);
}
As we can see it prints the whole function .What happen if we call the variable in which we store that function.
function outer(){
var a=10;
function inner(){
console.log(a);
}
return inner;
}
var store=outer();
store();
Output
10
How ?? Why ??
As we know that after executing the outer function it will pop out or deleted from the call stack so how it prints the value of a
which is present inside the outer function.
Their comes closure into picture.
The inner function always remember its lexical scope it knows where it was present in this case it is inside the outer function and inside the outer function the value of a
is 10 so that's why it will be able to give the value as 10.
In the above code when we return inner not just the function return but also the closure was return that closure involve function including with the lexical environment of the Parent.
Closure scope chain
Every closure has three scopes:
Local scope (Own scope)
Function scope
Global scope
In some cases it will also happen that our Outer function is itself a nested function then it will also access the outer function scope and from this way it will create a chain of function scopes.
Let's understand by writing the code.
// global scope
const e = 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 + e;
};
};
};
}
const sum2 = sum(1);
const sum3 = sum2(2);
const sum4 = sum3(3);
const result = sum4(4);
console.log(result);
Output
20
Lets understand what happen in the above code.
First sum will be executed and we will pass 1
to it. when it goes forward then it encounter a return statement.
Sum2 will store
sum2= return function sum2(b) {
return function sum3(c) {
return function sum4(d) {
return a + b + c + d + e;
Now sum2 will be executed and we will pass 2
to it.
Sum3 will store :
sum3=return function sum3(c) {
return function sum4(d) {
return a + b + c + d + e;
Now sum3 will be executed and we will pass 3 to it.
Sum4 will store:
sum4=return function sum4(d){
return function sum4(d) {
return a + b + c + d + e;
Now sum4 will be executed and we will pass 4 to it.
result will store
result=return a + b + c + d + e;
Now it will add all the value which we passed (1+2+3+4+10 =20)
10 here comes from the global variable which we defined at the top of our code.
console.log(result);
SO that's why it gives us the value as 20;
In the example above, there's a series of nested functions, all of which have access to the outer functions' scope. In this context, we can say that closures have access to all outer function scopes.
Closure is an important concept in JavaScript and little bit hard if you try to get in first time and you didn't get try code it by yourself and try to visualize it then it may be helpful for you.
That's it from now If you like it please give me a like and comment below the topic which you want me to cover.
Thank you