How JavaScript Code is executed? ❤️& Call Stack | Namaste JavaScript Ep. 2

How JavaScript Code is executed? ❤️& Call Stack | Namaste JavaScript Ep. 2

What Happens When You Run a JavaScript Program?

Understanding Execution Context

  • The execution context is fundamental to JavaScript, as it serves as the environment where code is executed. It is crucial for understanding how JavaScript operates.
  • Upon running a JavaScript program, an execution context is created. This context includes variables and functions defined in the program.

Phases of Execution Context Creation

Memory Creation Phase

  • The execution context consists of two components: the Memory Component and the Code Component. The creation phase allocates memory for all variables and functions.
  • During this first phase, known as the memory creation phase, JavaScript reserves space for each variable and function encountered in the code.
  • For variables like 'n', memory is allocated with an initial value of undefined. Functions have their entire code stored in memory during this phase.

Code Execution Phase

  • After memory allocation, the second phase begins—the code execution phase—where JavaScript executes the code line by line.
  • In this phase, actual values are assigned to variables. For example, when n = 2 is executed, 2 replaces undefined.

Function Invocation and New Execution Context

  • Invoking a function creates a new execution context within the existing one. Each function acts like a mini-program that has its own separate environment.

Execution Context Creation: Understanding Phases

Memory Creation Phase

  • The execution context creation involves two phases, starting with the memory creation phase where memory is allocated for variables and functions.
  • During this phase, only the relevant code (e.g., square(n)) is considered for memory allocation.
  • Memory is allocated to parameters like num and other variables; in this case, num and ans are initialized.
  • Initially, both num and ans are set to undefined, a special keyword that will be elaborated on in future discussions.

Code Execution Phase

  • The second phase is the code execution phase where each line of code is executed sequentially.
  • When the function is invoked, the value of n, which is 2, gets passed to the parameter num.
  • Here, it's important to distinguish between parameters (like num) and arguments (like n). In this instance, the argument's value of 2 replaces undefined in num.

Calculation Process

  • After assigning 2 to num, the next line calculates num * num, storing the result in ans.
  • The calculation results in 4 (since 2 * 2 = 4), replacing undefined in ans with this new value.

Return Statement

  • Upon reaching a return statement with ans, control returns back to where the function was invoked. This indicates completion of work within that context.
  • The return statement sends back the value of ans (which is now 4), effectively replacing undefined at its invocation point.

Cleanup After Execution

  • Once execution completes and control returns, the entire execution context for that function instance gets deleted from memory.
  • This deletion signifies that no trace remains of that specific execution context after returning a value.

New Function Invocation

  • A new function invocation occurs with an argument directly passing 4. This triggers another fresh execution context creation.
  • Similar steps follow as before: memory allocation occurs again for parameters like num and ans which start as undefined.

Second Execution Context Setup

Understanding JavaScript Execution Context

Code Execution and Function Invocation

  • The argument 4 is used in the code execution phase, replacing undefined. This leads to the calculation of num*num, resulting in 16.
  • After executing line 3, the value 16 replaces the previous undefined in the variable ans.
  • The return statement sends control back to line 7, where the function was invoked, updating square4 with the value 16.

Completion of Execution Context

  • Once function execution is complete, the entire execution context is deleted. This includes cleaning up after all operations are finished.
  • The global execution context is also removed after all tasks are completed, marking the end of JavaScript's work.

Phases of Execution Context Creation

  • The global execution context consists of two components: memory and code. It is created in two phases: memory creation and code execution.
  • During memory creation, variables and functions are allocated memory with an initial value of undefined. Functions store their entire code within this space.

Detailed Function Invocation Process

  • In the code execution phase, JavaScript executes each line sequentially. When a function is invoked (line 6), a new execution context is created.
  • Each invocation creates its own memory allocation for parameters like num and local variables such as ans, which stores results from calculations.

Managing Multiple Execution Contexts

  • As functions invoke other functions recursively, new contexts are created continuously. This can lead to complex management challenges for JavaScript engines.
  • Despite potential complexity from nested invocations, JavaScript handles these contexts efficiently through a structured approach.

Call Stack Mechanism

  • JavaScript uses a call stack to manage execution contexts. Each time a new context is created (e.g., when invoking a function), it gets pushed onto this stack.
  • The global execution context initializes at the bottom of this stack whenever any JS program runs.

Control Flow Through Call Stack

  • Upon completing an executed function (E1), it pops off from the stack returning control back to where it left off in the global context.
  • New contexts continue to be added or removed from this stack as functions execute or complete their tasks.

Finalization of Program Execution

  • After all executions finish, both individual contexts and the global one are cleared from the call stack.

Understanding JavaScript's Call Stack

The Confusion Surrounding JavaScript

  • JavaScript is described as the most confusing and misunderstood programming language, highlighting its complexity.
  • The call stack, also referred to by various names such as Execution Context Stack, Program Stack, Control Stack, Runtime Stack, and Machine Stack, serves a crucial role in execution order.
  • The call stack maintains the sequence of execution for different execution contexts within JavaScript.
  • Understanding the call stack is essential for grasping how JavaScript manages function calls and execution flow.
Video description

Understand how the code is executed in JavaScript. How an Execution Context is created and how the Call Stack works. Behind the scenes, there are a lot of things happening in JS Engine when the code is executed. All core fundamentals are covered in this video with examples. With this code example in the video, you'll understand how things are working under the hood of javascript when code is executed. You'll get to know what exactly happens when you invoke a function in JavaScript. This js tutorial covers various underlying core fundamentals in depth. My tech gear I use every day - http://google.peek.link/2pba Topics Covered: 00:00 - What happens when you run JavaScript Code? 00:32 - Code Example for Execution Context Creation 01:03 - Global Execution Context Creation 01:20 - Memory Allocation Phase & Code Execution Phase 05:56 - Function Invocation and Execution Context Creation 11:15 - What happens while executing return statement 16:35 - Recap of Code Execution synchronously 19:26 - Call Stack in JavaScript 22:21 - Other names of the Call Stack in JS 23:10 - Thank you for watching Namaste JavaScript 🙏 Support this video series, NOT BY MONEY, but by sharing it with your friends. 🙏 I'll give my best to come up with great content and everything absolutely for free on YouTube. 😊 If you are active on Social Media, please give a shoutout to Namaste JavaScript and help me reach more people. 🙏 Cheers, Akshay Saini http://akshaysaini.in Would love to Stay Connected with you ❤️ LinkedIn - https://www.linkedin.com/in/akshaymarch7 Instagram - https://www.instagram.com/akshaymarch7 Twitter - https://twitter.com/akshaymarch7 Facebook - https://www.facebook.com/akshaymarch7 #NamasteJS #AkshaySaini