DEV Community

kim-jos
kim-jos

Posted on • Updated on

How is JS Code Executed?

What happens when you run JS code?

Phase 1: Memory Creation Phase
First, a global execution context is created. Second, JS allocates memory to all variables and functions. Variables are initially assigned undefined values while functions are copied wholly instead of assigning values of undefined like variables which is also why hoisting is possible but we will get to that later.
Phase 2: Code Execution Phase (code is executed from top to bottom)
The actual values of the variables are assigned and functions are invoked.
Phase 3: All the execution contexts including the global execution context are popped off once the code is done executing.

What happens when a function is invoked?

When a function is invoked a new execution context is created with a memory and code execution component. It goes through the same two phases mentioned previously. It first allocates memory to variables and functions then it executes the code.

What happens while executing a return statement?

It returns the function to the place that it was invoked.

Let's go over the whole process with following code.

var a = 3;
function aMultiply (num) {
  var result = num * num;
  return result
}
var aMultiply1 = aMultiply(a);
var aMultiply2 = aMultiply(4);
Enter fullscreen mode Exit fullscreen mode

First, the global execution context is created assigning variables a, aMultiply1, & aMultiply2 with undefined values. Functions are copied to the memory component. Let's see how this actually works in the browser. I put a debugger in line 2 in the following image. As you can see in the scope section, the variables have values of undefined while functions have the entire function copied to the memory.

image

Second, the code is executed one by one. If there is a variable, the actual value is assigned which would be 3 in this case for var a. Functions do not need to be assigned a value because it is already copied in the memory component.
If a function is invoked like in var aMultiply1, another execution context is created. The same process of allocating memory and executing code is repeated until the function is returned. Once the function is returned it goes back(or returns) to the place that it was invoked which would be to var multiply1 in this case. Then it would proceed to invoke aMultiply2.

As you can see in the snapshot below, when aMultiply1 is invoked another execution context is created in the call stack.

image

What is the call stack?

JS manages this whole process mentioned above using a call stack. First the global execution is pushed into the stack before code is even executed. Then when a function is invoked a new execution context is pushed into the stack. When the function is returned it is popped off the stack. JS continues to run until the global execution context is popped off and the call stack is empty.

Top comments (0)