DEV Community

Salman Hassan
Salman Hassan

Posted on

Javascript Execution Context

🚀 𝐔𝐧𝐝𝐞𝐫𝐬𝐭𝐚𝐧𝐝𝐢𝐧𝐠 𝐉𝐚𝐯𝐚𝐒𝐜𝐫𝐢𝐩𝐭 𝐄𝐱𝐞𝐜𝐮𝐭𝐢𝐨𝐧 𝐂𝐨𝐧𝐭𝐞𝐱𝐭 📚

🔍 𝑾𝒉𝒂𝒕 𝒊𝒔 𝒂𝒏 𝑬𝒙𝒆𝒄𝒖𝒕𝒊𝒐𝒏 𝑪𝒐𝒏𝒕𝒆𝒙𝒕?
When JavaScript code starts running, it creates a special environment called the 𝘎𝘭𝘰𝘣𝘢𝘭 𝘌𝘹𝘦𝘤𝘶𝘵𝘪𝘰𝘯 𝘊𝘰𝘯𝘵𝘦𝘹𝘵 (𝘎𝘌𝘊). Think of it as a container that holds everything related to your script.

🔹 𝘊𝘰𝘮𝘱𝘰𝘯𝘦𝘯𝘵𝘴 𝘰𝘧 𝘢𝘯 𝘌𝘹𝘦𝘤𝘶𝘵𝘪𝘰𝘯 𝘊𝘰𝘯𝘵𝘦𝘹𝘵

A GEC has two main parts:

  1. 🧠 𝘔𝘦𝘮𝘰𝘳𝘺: Stores variables and functions.
  2. 📝 𝘊𝘰𝘥𝘦: Contains the actual JavaScript code.

🔄 Creation of an Execution Context

The GEC is created in two phases:

  1. 🛠️ 𝑪𝒓𝒆𝒂𝒕𝒊𝒐𝒏 𝑷𝒉𝒂𝒔𝒆:

📦 𝘔𝘦𝘮𝘰𝘳𝘺 𝘈𝘭𝘭𝘰𝘤𝘢𝘵𝘪𝘰𝘯: All variables are allocated memory and initialized with 𝘶𝘯𝘥𝘦𝘧𝘪𝘯𝘦𝘥.

🔍 𝘍𝘶𝘯𝘤𝘵𝘪𝘰𝘯 𝘋𝘦𝘤𝘭𝘢𝘳𝘢𝘵𝘪𝘰𝘯𝘴: Functions are stored in memory as complete code blocks. This is known as 𝘩𝘰𝘪𝘴𝘵𝘪𝘯𝘨.

  1. ⚙️ 𝑬𝒙𝒆𝒄𝒖𝒕𝒊𝒐𝒏 𝑷𝒉𝒂𝒔𝒆:

▶️ Code Execution: The code is executed line by line.

📌 Variable Assignment: Variables are assigned their actual values.

📞 Function Invocation: When a function is called, a new execution context is created for that function and pushed onto the 𝘤𝘢𝘭𝘭 𝘴𝘵𝘢𝘤𝘬.

🔚 Return: Once the function finishes, its context is popped off the stack, and execution returns to the previous context.

🔑 𝑺𝒄𝒐𝒑𝒆 𝒂𝒏𝒅 𝑯𝒐𝒊𝒔𝒕𝒊𝒏𝒈

🌐 𝑺𝒄𝒐𝒑𝒆 : Determines the accessibility of variables. Variables declared within a function have function scope, while those declared outside have global scope.

🔼 𝑯𝒐𝒊𝒔𝒕𝒊𝒏𝒈: Function declarations and variable declarations are moved to the top of their scope during the creation phase, but variable assignments remain in their original positions.

Top comments (0)