How functions are executed in JavaScript?

Photo by Joan Gamell on Unsplash

How functions are executed in JavaScript?

·

2 min read

This blog explores the concept internal working of functions in JavaScript for beginners. Function are one of the most important of an object oriented programming language like C++, Java or JavaScript.

Before knowing how functions are execute one must know that in JavaScript an execution context is formed where things such as variables and functions are defined in memory of the execution context. Initially, the are undefined in case of the variable and for functions we will talk about it few lines later.

var a = 10
var b = 20

For above code, we can define the execution context in two steps:

Step 1: Variables are stored in memory and are still not defined as values are not assigned.

MemoryAllocation
aundefined
bundefined

Step 2: Variables are assigned for each of the variable name:

MemoryAllocation
a10
b20

But, in case of functions when they are defined an inner execution context is also set as shown:

function(){
    var a = 10
    console.log(a)
}

Here in global execution context the function is defined and after that an another global execution is created in while memory allocation and in the secondary execution context variable is established as undefined and value is assigned to it in secondary allocation.

Step 1:

Step 2:

Step 3: