How JavaScript Works and its Execution Context

How JavaScript Works and its Execution Context

Introduction

In this blog, we're going to talk about JavaScript—what it is, how it works, and why it's important. We'll also touch on something interesting called the Execution Context.

As you know HTML is the basic structure or skeleton of a webpage. CSS helps make it look good. Now, to make things happen on that webpage, we need JavaScript.

In simpler terms:

JavaScript is a type of code that lets us do cool things on a website. like what will happen when we click the button.

What is Javascript -

"Javascript is a Synchronous Single Threaded Language"

Here I throw some jargon Let me explain these one by one -

Synchronous - Synchronous means Doing things one after the other, like waiting in line.

Single Threaded- Handling one task at a time, like a superhero with a single focus.

"Synchronous Single Threaded Language" means that it follows a step-by-step order, and handles one task at a time.

Execution Context

Now Let's talk about Execution Context -

Firstly all Javascript code runs inside the Execution Context, we have two main things inside the Execution Context -

  1. Memory Component - Here all the Variables and Functions are stored in Key-Value pairs.

  2. Code Component - Here Code is executed one line at a time, it is also known as Thread of Execution.

Now Let's understand this with an example -

Here in the first step, Javascript scans the whole code and allocates all the memory to the variables and functions.

In the case of a Variable, it is defined as undefined, and in the case of functions, it stores all the code inside the value.
This introduces a crucial concept known as "Hoisting" which we will delve into in upcoming blogs.

Now the second step is to start the Code Execution-

In place of sideLength the value of undefined is replaced by 2.

In the Next line when the function executes a whole new execution context will be created for this.

Now as you see in the image for the function call brand new execution context will be created and in the Memory Component phase it comes with area and length values(undefined) because this time Memory Component is executing.

In the Code Component, 3 is passed as an argument so the value of length is changed to 3 in this. and now here it calculates the area and when it sees the return statement it gives all things to there where it's called.

Now the rectangle1 value will be changed to the area.

Here's how the execution context works in Javascript, Now for better understanding create the execution Context for line No. 9 Code.

For managing all this Javascript uses a call Stack, It's a data structure that the JavaScript engine uses to manage the execution. When a function is called, an Execution Context is added to the top of the call stack. As the function completes, its frame is removed from the stack.

Thanks For Checking this, Happy Coding 🎉

.