
- Javascript Basics Tutorial
- Javascript - Home
- JavaScript - Roadmap
- JavaScript - Overview
- JavaScript - Features
- JavaScript - Enabling
- JavaScript - Placement
- JavaScript - Syntax
- JavaScript - Hello World
- JavaScript - Console.log()
- JavaScript - Comments
- JavaScript - Variables
- JavaScript - let Statement
- JavaScript - Constants
- JavaScript - Data Types
- JavaScript - Type Conversions
- JavaScript - Strict Mode
- JavaScript - Reserved Keywords
- JavaScript Operators
- JavaScript - Operators
- JavaScript - Arithmetic Operators
- JavaScript - Comparison Operators
- JavaScript - Logical Operators
- JavaScript - Bitwise Operators
- JavaScript - Assignment Operators
- JavaScript - Conditional Operators
- JavaScript - typeof Operator
- JavaScript - Nullish Coalescing Operator
- JavaScript - Safe Assignment Operator
- JavaScript - Delete Operator
- JavaScript - Comma Operator
- JavaScript - Grouping Operator
- JavaScript - Yield Operator
- JavaScript - Spread Operator
- JavaScript - Exponentiation Operator
- JavaScript - Operator Precedence
- JavaScript Control Flow
- JavaScript - If...Else
- JavaScript - While Loop
- JavaScript - For Loop
- JavaScript - For...in
- Javascript - For...of
- JavaScript - Loop Control
- JavaScript - Break Statement
- JavaScript - Continue Statement
- JavaScript - Switch Case
- JavaScript - User Defined Iterators
- JavaScript Functions
- JavaScript - Functions
- JavaScript - Function Expressions
- JavaScript - Function Parameters
- JavaScript - Default Parameters
- JavaScript - Function() Constructor
- JavaScript - Function Hoisting
- JavaScript - Self-Invoking Functions
- JavaScript - Arrow Functions
- JavaScript - Function Invocation
- JavaScript - Function call()
- JavaScript - Function apply()
- JavaScript - Function bind()
- JavaScript - Closures
- JavaScript - Variable Scope
- JavaScript - Global Variables
- JavaScript - Smart Function Parameters
- JavaScript Objects
- JavaScript - Number
- JavaScript - Boolean
- JavaScript - Strings
- JavaScript - Arrays
- JavaScript - Date
- JavaScript - DataView
- JavaScript - Handler
- JavaScript - Math
- JavaScript - RegExp
- JavaScript - Symbol
- JavaScript - Sets
- JavaScript - WeakSet
- JavaScript - Maps
- JavaScript - WeakMap
- JavaScript - Iterables
- JavaScript - Reflect
- JavaScript - TypedArray
- JavaScript - Template Literals
- JavaScript - Tagged Templates
- Object Oriented JavaScript
- JavaScript - Objects
- JavaScript - Classes
- JavaScript - Object Properties
- JavaScript - Object Methods
- JavaScript - Static Methods
- JavaScript - Display Objects
- JavaScript - Object Accessors
- JavaScript - Object Constructors
- JavaScript - Native Prototypes
- JavaScript - ES5 Object Methods
- JavaScript - Encapsulation
- JavaScript - Inheritance
- JavaScript - Abstraction
- JavaScript - Polymorphism
- JavaScript - Destructuring
- JavaScript - Destructuring Assignment
- JavaScript - Object Destructuring
- JavaScript - Array Destructuring
- JavaScript - Nested Destructuring
- JavaScript - Optional Chaining
- JavaScript - Global Object
- JavaScript - Mixins
- JavaScript - Proxies
- JavaScript Versions
- JavaScript - History
- JavaScript - Versions
- JavaScript - ES5
- JavaScript - ES6
- ECMAScript 2016
- ECMAScript 2017
- ECMAScript 2018
- ECMAScript 2019
- ECMAScript 2020
- ECMAScript 2021
- ECMAScript 2022
- JavaScript Asynchronous
- JavaScript - Asynchronous
- JavaScript - Callback Functions
- JavaScript - Promises
- JavaScript - Async/Await
- JavaScript - Microtasks
- JavaScript - Promisification
- JavaScript - Promises Chaining
- JavaScript - Timing Events
- JavaScript - setTimeout()
- JavaScript - setInterval()
- JavaScript Cookies
- JavaScript - Cookies
- JavaScript - Cookie Attributes
- JavaScript - Deleting Cookies
- JavaScript Browser BOM
- JavaScript - Browser Object Model
- JavaScript - Window Object
- JavaScript - Document Object
- JavaScript - Screen Object
- JavaScript - History Object
- JavaScript - Navigator Object
- JavaScript - Location Object
- JavaScript - Console Object
- JavaScript Web APIs
- JavaScript - Web API
- JavaScript - History API
- JavaScript - Storage API
- JavaScript - Forms API
- JavaScript - Worker API
- JavaScript - Fetch API
- JavaScript - Geolocation API
- JavaScript Events
- JavaScript - Events
- JavaScript - DOM Events
- JavaScript - addEventListener()
- JavaScript - Mouse Events
- JavaScript - Keyboard Events
- JavaScript - Form Events
- JavaScript - Window/Document Events
- JavaScript - Event Delegation
- JavaScript - Event Bubbling
- JavaScript - Event Capturing
- JavaScript - Custom Events
- JavaScript Error Handling
- JavaScript - Error Handling
- JavaScript - try...catch
- JavaScript - Debugging
- JavaScript - Custom Errors
- JavaScript - Extending Errors
- JavaScript Important Keywords
- JavaScript - this Keyword
- JavaScript - void Keyword
- JavaScript - new Keyword
- JavaScript - var Keyword
- JavaScript HTML DOM
- JavaScript - HTML DOM
- JavaScript - DOM Methods & Properties
- JavaScript - DOM Document
- JavaScript - DOM Elements
- JavaScript - DOM Attributes (Attr)
- JavaScript - DOM Forms
- JavaScript - Changing HTML
- JavaScript - Changing CSS
- JavaScript - DOM Animation
- JavaScript - DOM Navigation
- JavaScript - DOM Collections
- JavaScript - DOM NodeList
- JavaScript - DOM DOMTokenList
- JavaScript Advanced Chapters
- JavaScript - Bubble Sort Algorithm
- JavaScript - Circular Reference Error
- JavaScript - Code Testing with Jest
- JavaScript - CORS Handling
- JavaScript - Data Analysis
- JavaScript - Dead Zone
- JavaScript - Design Patterns
- JavaScript - Engine and Runtime
- JavaScript - Execution Context
- JavaScript - Function Composition
- JavaScript - Immutability
- JavaScript - Kaboom.js
- JavaScript - Lexical Scope
- JavaScript - Local Storage
- JavaScript - Memoization
- JavaScript - Minifying JS
- JavaScript - Mutability vs Immutability
- JavaScript - Package Manager
- JavaScript - Parse S-Expressions
- JavaScript - Prototypal Inheritance
- JavaScript - Reactivity
- JavaScript - Require Function
- JavaScript - Selection API
- JavaScript - Session Storage
- JavaScript - SQL CRUD Operations
- JavaScript - Supercharged Sorts
- JavaScript - Temporal Dead Zone
- JavaScript - Throttling
- JavaScript - TRPC Library
- JavaScript - Truthy and Falsy Values
- JavaScript - Upload Files
- JavaScript - Date Comparison
- JavaScript - Recursion
- JavaScript - Data Structures
- JavaScript - Base64 Encoding
- JavaScript - Callback Function
- JavaScript - Current Date/Time
- JavaScript - Date Validation
- JavaScript - Filter Method
- JavaScript - Generating Colors
- JavaScript - HTTP Requests
- JavaScript - Insertion Sort
- JavaScript - Lazy Loading
- JavaScript - Linked List
- JavaScript - Nested Loop
- JavaScript - Null Checking
- JavaScript - Get Current URL
- JavaScript - Graph Algorithms
- JavaScript - Higher Order Functions
- JavaScript - Empty String Check
- JavaScript - Form Handling
- JavaScript - Functional Programming
- JavaScript - Parameters vs Arguments
- JavaScript - Prototype
- JavaScript - Reactive Programming
- JavaScript - Reduce Method
- JavaScript - Rest Operator
- JavaScript - Short Circuiting
- JavaScript - Undefined Check
- JavaScript - Unit Testing
- JavaScript - Validate URL
- JavaScript Miscellaneous
- JavaScript - Ajax
- JavaScript - Async Iteration
- JavaScript - Atomics Objects
- JavaScript - Rest Parameter
- JavaScript - Page Redirect
- JavaScript - Dialog Boxes
- JavaScript - Page Printing
- JavaScript - Validations
- JavaScript - Animation
- JavaScript - Multimedia
- JavaScript - Image Map
- JavaScript - Browsers
- JavaScript - JSON
- JavaScript - Multiline Strings
- JavaScript - Date Formats
- JavaScript - Get Date Methods
- JavaScript - Set Date Methods
- JavaScript - Modules
- JavaScript - Dynamic Imports
- JavaScript - BigInt
- JavaScript - Blob
- JavaScript - Unicode
- JavaScript - Shallow Copy
- JavaScript - Call Stack
- JavaScript - Reference Type
- JavaScript - IndexedDB
- JavaScript - Clickjacking Attack
- JavaScript - Currying
- JavaScript - Graphics
- JavaScript - Canvas
- JavaScript - Debouncing
- JavaScript - Performance
- JavaScript - Style Guide
JavaScript - Execution Context
We will learn about the JavaScript execution context in this chapter, where we will also cover its types, definition, execution stack, creation process, and overall execution phase. We will go over each topic individually. First, let's get started with the introduction.
What is Execution Context?
The execution context is a term that describes the internal workings of code. The JavaScript Execution Context describes the environment in which JavaScript code can be run. The execution context specifies which code sections have access to the functions, variables and objects used in the code.
During the execution context, the given code is parsed line by line, with variables and functions kept in memory. An execution context is similar to a container for storing variables; code is evaluated and then executed. So, the execution context provides an environment in which specific code can be executed.
Types of Execution Context
The JavaScript execution context types are as follows −
Global Execution Context/GEC
Functional Execution Context/FEC
Eval Execution Context
Now let us discuss each type one by one in the below section −
Global Execution Context
GEC (Global Execution Context) is often referred to as the base or default execution. Any JavaScript code that does not occur in a function will be found in the global execution context. The word 'default execution context' refers to the fact that the code is executed when the file is first loaded into the web browser. GEC carries out the following two tasks −
First, it creates a global object for Node.js and a window object for browsers.
Second, use the keyword 'this' to refer to the Windows object.
Create a memory heap to store variable and function references.
Then it stores all function declarations in the memory heap and initializes all variables in the GEC with 'undefined'.
Because the JS engine is single-threaded, there is only one global environment that may be used to execute JavaScript code.
Functional Execution Context
FEC, or Functional Execution Code, is the type of context generated by the JavaScript engine when a function call is found. Because each function has its own execution context, the FEC, unlike the GEC, can have multiple instances. Also, the FEC has access to the whole GEC code, while the GEC does not have access to all of the FEC's code. During GEC code execution, a function call is initiated, and when the JS engine finds it, it generates a new FEC for that function.
Eval Function Execution Context
Any JavaScript code executed using the eval function creates and retains its own execution context. But JavaScript developers do not use the eval function which is a component of the Execution Context.
Phases of the Execution Context in JS
There are 2 main phases of JavaScript execution context −
Creation Phase: In the creation phase, the JavaScript engine establishes the execution context and configures the script's environment. It sets the values of variables and functions as well as the execution context's scope chain.
Execution Phase: In this phase, the JavaScript engine runs the code in the execution context. It parses any statements or expressions in the script and evaluates any function calls.
Everything in JavaScript works within this execution context. It is divided into two parts. One is memory and the other one is code. It is important to keep in mind that these phases and components are applicable to both global and functional execution settings.
Creation Phase
Let us see the below example −
var n = 6; function square(n) { var ans = n * n; return ans; } var sqr1 = square(n); var sqr2 = square(8); console.log(sqr1) console.log(sqr2)
Output
This will generate the below result −
36 64
Initially, the JavaScript engine executes the full source code, creates a global execution context and then performs the following actions −
Creates a global object that is a window in the browser and global in Node.js.
Creates a memory for storing variables and functions.
Stores variables with undefined values and function references.
After the creation phase the execution context will be moved to the code execution phase.
Execution Phase
During this step, it begins running over the entire code line by line from top to bottom. When it finds n = 5, it assigns the value 5 to the memory variable 'n'. Initially, the value of 'n' was undefined by default.
Then we get to the 'square' function. Because the function has been allocated memory, it goes right to the line var square1 = square(n);. square() is then invoked, and JavaScript creates a new function execution context.
When the calculation is finished, it assigns the value of square to the previously undefined 'ans' variable. The function will return its value and the function execution context will be removed.
The value generated by square() will be assigned to square1. This also applies to square two. Once all of the code has been executed, the global context will look like this and will be erased.
Execution Stack
The JavaScript engine uses a call stack to keep track of all contexts, both global and functional. A call stack is also referred to as a Execution Context Stack, Runtime Stack or Machine Stack.
It follows the LIFO concept (Last-In-First-Out). When the engine initially starts processing the script, it generates a global context and pushes it to the stack. When a function is invoked, the JS engine constructs a function stack context, moves it to the top of the call stack and begins executing it.
When the current function completes the JavaScript engine removes the context from the call stack and returns it to its parent. Let us check the below example code −
function firstFunc(m,n) { return m * n; } function secondFunc(m,n) { return firstFunc(m,n); } function getResult(num1, num2) { return secondFunc(num1, num2) } var res = getResult(6,7); console.log("The result is:", res);
Output
This will produce the below result −
The result is: 42
In this case, the JS engine creates a global execution context and starts the creation process.
It initially allocates memory for firstFunc, secondFunc, the getResult function, and the res variable. Then it invokes getResult(), which is pushed to the call stack.
Then getResult() calls secondFunc(). At this point, secondFunc's context will be saved to the top of the stack. Then it will begin execution and invoke another function, firstFunc(). Similarly function A's context will be pushed.
After execution of each function it is removed from the call stack.
The call stack's size is determined by the operating system or browser. If the number of contexts exceeds the limit a stack overflow error will be returned. This happens when a recursive function has a base condition.
function display() { display(); } display();
Output
This will generate the below result −
C:\Users\abc\Desktop\Javascript\example.js:2 display(); ^ RangeError: Maximum call stack size exceeded
Summary
Finally, understanding how JavaScript works behind the scenes needs knowledge of the execution context. It defines the environment in which code is executed as well as the variables and functions available for use.
The method of building involves creating the global and function execution contexts, the scope chain and allocating memory for the variables and functions. During the execution step the JavaScript engine goes over the code line by line. This includes evaluating and executing statements.