Hoisting in JS
Hoisting is a JavaScript mechanism where variables and function declarations are moved to the top of their scope before code execution.
One of the advantages of JavaScript putting function declarations into memory before it executes any code segment is that it allows you to use a function before you declare it in your code. For example:
function print(name) {
console.log("My name is " + name);
}
print("Abhay");
/*
The result of the code above is: "My name is Abhay"
*/
The above code snippet is how you would expect to write the code for it to work. Now, let’s see what happens when we call the function before we write it:
print("Abhay");function print(name) {
console.log("My name is " + name);
}
/*
The result of the code above is: "My name is Abhay"
*/
Even though we call the function in our code first, before the function is written, the code still works. This is because of how context execution works in JavaScript.
Hoisting works well with other data types and variables. The variables can be initialized and used before they are declared.
JavaScript only hoists declarations, not initializations.
console.log(num); // Returns undefined, as only declaration was hoisted, no initialization has happened at this stage
var num; // Declaration
num = 6; // Initialization
The example below only has initialization. No hoisting happens so trying to read the variable results in ReferenceError exception.
console.log(num); // Throws ReferenceError exception
num = 6; // Initialization
Initializations using let
and const
are also not hoisted.
// Example with let:
a = 1; // initialization.
let a; // Throws ReferenceError: Cannot access 'a' before initialization
// Example with const:
a = 1; // initialization.
const a; // Throws SyntaxError: Missing initializer in const declaration