What is Hoisting?
Hoisting is the term used to describe the moving of variables and functions to the top of their (global or function) scope on where we define that variable or function.
Ok to understand Hoisting, I have to explain the execution context. The Execution Context is the "environment of code" that is currently executing. The Execution Context has two phases compilation and execution.
Compilation - in this phase it gets all the function declarations and hoists them up to the top of their scope so we can reference them later and gets all variables declaration (declare with the var keyword) and also hoists them up and give them a default value of undefined.
Execution - in this phase it assigns values to the variables hoisted earlier and it executes or invokes functions (methods in objects).
Note: only function declarations and variables declared with the var keyword are hoisted not function expressions or arrow functions, let and const keywords.
Ok, suppose we have an example code in the global scope below.
console.log(y);y = 1;console.log(y);console.log(greet('Mark'));function greet(name) {return 'Hello ' + name + '!';}var y;
This code logs undefined
, 1
, Hello Mark!
respectively.
So the compilation phase would look like this.
function greet(name) {return 'Hello ' + name + '!';}var y; //implicit "undefined" assignment//waiting for "compilation" phase to finish//then start "execution" phase/*console.log(y);y = 1;console.log(y);console.log(greet("Mark"));*/
for example purposes, I commented on the assignment of variable and function call.
After the compilation phase finishes it starts the execution phase invoking methods and assigns values to variables.
function greet(name) {return 'Hello ' + name + '!';}var y;//start "execution" phaseconsole.log(y);y = 1;console.log(y);console.log(greet('Mark'));
Read more
December 04, 2022
JavaScriptDecember 04, 2022
JavaScriptDecember 02, 2022
JavaScript