Javascript Execution Context

Salman Hassan - Aug 9 - - Dev Community

๐Ÿš€ ๐”๐ง๐๐ž๐ซ๐ฌ๐ญ๐š๐ง๐๐ข๐ง๐  ๐‰๐š๐ฏ๐š๐’๐œ๐ซ๐ข๐ฉ๐ญ ๐„๐ฑ๐ž๐œ๐ฎ๐ญ๐ข๐จ๐ง ๐‚๐จ๐ง๐ญ๐ž๐ฑ๐ญ ๐Ÿ“š

๐Ÿ” ๐‘พ๐’‰๐’‚๐’• ๐’Š๐’” ๐’‚๐’ ๐‘ฌ๐’™๐’†๐’„๐’–๐’•๐’Š๐’๐’ ๐‘ช๐’๐’๐’•๐’†๐’™๐’•?
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.

.
Terabox Video Player