Understanding Execution Context, Thread, and Functions in Javascript

dipakkr

Deepak Kumar

Posted on October 21, 2020

Understanding Execution Context, Thread, and Functions in Javascript

In today's post, I am going to write about how javascript works. We will throw some light on terminologies like Execution context, function level execution context, function invoking, and threads.

*Do you know what happens behind the scene when you run a javascript code? *

Let's take an example of the below code snippet.

const a = 10;

function add(x, y){
    const result = x + y;
    return result;
}

const name = 'github';
const final = add(10, 20);

Enter fullscreen mode Exit fullscreen mode

As soon as you run this program, it creates a Global Execution Content, the place where the javascript thread will run line by line and run your code.

You can think of Global execution context as an environment where the code runs.

There can be multiple execution context in a program but a single Global execution context.

Now let's go back to the above code snippet and see what the JS engine does when we run the code.

  • JS Engine parses your code line by line & identifies variables & functions created by code (which will be used in the execution phase)

  • JS Engine setup memory space for variables & functions ( called as Hoisting)

*Hoisting * is basically the JS Engine set-asides memory space for variables and functions used inside the code before your code is executed. These variables & functions comprise the Execution Context of any function that is being executed.

  • A new Execution Context is created whenever function invocation is called.

All variables in JS are initially set to undefined.

Alt Text

Let's take one more example.

function y(){
    const p = 100;
}

function x(){
    y();
    const t = 10;
}

x();
const r = 20;
Enter fullscreen mode Exit fullscreen mode

EC : Execution Context

When we run this code, here is what the Javascript engine does.

  • First, a Global Execution Context is going to be created.

  • Interpreter encounters call x(), and again a new EC is created for x.

  • Now the EC for x is created it will run the code line by line inside x.

  • Inside x, a new function call y() is invoked, it again creates an EC for y.

  • When y is finished running, it will back to EC of x, and variable t is assigned.

  • After x run is finished, it will be back to Global EC, and variable r is assigned.

  • Global EC finishes running and the program stops.

In tomorrow's blog, I will explain how the call stack works in Javascript. I would love to know your feedback on this blog.


Stay tuned - Follow me on Twitter

💖 💪 🙅 🚩
dipakkr
Deepak Kumar

Posted on October 21, 2020

Join Our Newsletter. No Spam, Only the good stuff.

Sign up to receive the latest update from our blog.

Related