JavaScript Execution Context & Hoisting
A summarized note about what I learned on
Execution Context
andHoisting
of JS.
Execution Context
Execution Context is simply the environment where JavaScript codes run. It has two types, Global and Function, which work as below:
- When a code is executed, a new execution context with a stack (LIFO) structure is created(
call stack
). - When the control is on the global code, Global Execution Context is created and stacked on the execution context. The global execution context exists until the application is finished (either leaving the web page or closing the browser).
- When a function is called, its Function Execution Context is created and stacked on top of the execution context of the code block executed before. When it is done, the function execution context is discarded and its control is returned to the previous execution context.
Stage of Execution Context
Each context also has two stages also: Creation and Execution.
Global Execution Context
Creation phase
- Create a
global
object - Init all
var
variables toundefined
and store the initialized variables and declared function into a memory heap (a.k.a.hoisting
- Bind
this
to the global object
Execution phase
- Assign a value to variables
- Execute each function - when a function in the global code starts executing, a new function execution context is created for every function.
Function Execution Context
Creation phase
- Create an
argument
object, which contains references to all the parameters - Init arguments to
undefined
, and store them into a memory heap - Determine
this
value - a value assigned tothis
will be determined by the function call.
Execution phase
- Assign a value to variables
- Execute inner functions and create each function execution context
Hoisting
Hoisting is the process of putting all variable and function declarations into memory during the creation phase of the execution context. In JavaScript, functions are fully hoisted, var
variables are hoisted and initialized to undefined, and let
and const
variables are hoisted but not initialized a value. We should avoid hoisting
by using let
and const
as much as possible because it can cause memory leaks and make debugging hard.
var favouriteFood = "grapes";
var foodThoughts = function () {
console.log("Original favourite food: " + favouriteFood); // undefined
var favouriteFood = "sushi";
console.log("New favourite food: " + favouriteFood); // sushi
};
foodThoughts();
function bigBrother(){
function littleBrother() {
return 'it is me!';
}
return littleBrother();
function littleBrother() {
return 'no me!';
}
}
bigBrother(); // no me!
Sources
Udemy course - JavaScript: The Advanced Concepts Poiemaweb JavaScript Tutorial Parameter vs. Arguments