Understanding execution context and stack to become a better JavaScript developer.
If you are or want to be a JavaScript developer, then you must know how the JavaScript programs are executed internally. The understanding of execution context and execution stack is vital in order to understand other JavaScript concepts such as Hoisting, Scope, and Closures.
Properly understanding the concept of execution context and execution stack will make you a much better JavaScript developer.
So without further ado, let’s get started :)
Simply put, an execution context is an abstract concept of an environment where the Javascript code is evaluated and executed. Whenever any code is run in JavaScript, it’s run inside an execution context.
There are three types of execution context in JavaScript.
this
to equal to the global object. There can only be one global execution context in a program.eval
function also gets its own execution context, but as eval
isn’t usually used by JavaScript developers, so I will not discuss it here.Execution stack, also known as “calling stack” in other programming languages, is a stack with a LIFO (Last in, First out) structure, which is used to store all the execution context created during the code execution.
When the JavaScript engine first encounters your script, it creates a global execution context and pushes it to the current execution stack. Whenever the engine finds a function invocation, it creates a new execution context for that function and pushes it to the top of the stack.
The engine executes the function whose execution context is at the top of the stack. When this function completes, its execution stack is popped off from the stack, and the control reaches to the context below it in the current stack.
Let’s understand this with a code example below:
let a = 'Hello World!';function first() {
console.log('Inside first function');
second();
console.log('Again inside first function');
}function second() {
console.log('Inside second function');
}first();
console.log('Inside Global Execution Context');
#javascript #web-development #developer