Hoisting Explained

Payal RatheePayal Rathee
2 min read

Javascript executes in two phases:

  1. Creation Phase: In this phase, JS allocates space in memory for all the variables, constants, functions, etc. This phase actually creates the execution contexts.

  2. Execution phase: In this phase, all the assignments, function calls, etc. are executed using the context created in previous phase.

So, Hoisting is actually Javascripts mechanism of gathering all the variables, constants, etc. that will be required in a function and allocate their space in the memory. It doesn’t initialize in the creation phase, variables remain undefined.

Lets take an example to understand it better,

Lets look at each one:

  • let/const - gets hoisted but resides in the Temporal Dead Zone(TDZ) and can’t be accessed.

  • var - hoisted and set to undefined, can be accessed.

  • function definitions - hoisted, therefore, functions can be called anywhere in the scope.

  • function assignments - only the variable holding the function gets hoisted and set to undefined.

  • class definition - hoisted, but can’t be initialized constructor is not yet available.

Lets understand it by taking a few more examples:

f();
function f() {
    console.log("Hello");
}

/* Output: Hello
f gets hoisted during creation phase, hence it is available in execution phase before 
definition.
*/
f();
const f = function() {
    console.log("Hello");
}
/* Throws error: Cannot access 'f' before initialization
f variable gets hoisted during creation phase and set to undefined, it is not available until
it gets assigned in execution phase.
*/
console.log(a);
var a = 10;

/* Output: undefined
a gets hoisted during creation and set to undefined 
*/
console.log(a);
let a = 10;
/* Throws error: Cannot access 'a' before initialization
a gets hoisted but resided in TDZ and can't be accesses until initialized in execution phase
*/
const p = new Person()
class Person {
    constructor() {
        this.name = "Demo"
    }
}
/* Throws error: Cannot access 'Person' before initialization
class gets hoisted but not the constructor
*/

Hoisting is JavaScript's behavior of moving declarations to the top of their enclosing scope during the compilation phase, before the code is actually executed.

Note that variables are not physically moved at the top rather it is logically percieved as they are available before the code actually starts execution.

0
Subscribe to my newsletter

Read articles from Payal Rathee directly inside your inbox. Subscribe to the newsletter, and don't miss out.

Written by

Payal Rathee
Payal Rathee