Hoisting in JS

Hoisting is a JavaScript mechanism where variables and function declarations are moved to the top of their scope before code execution.

function print(name) {
console.log("My name is " + name);
}

print("Abhay");

/*
The result of the code above is: "My name is Abhay"
*/
print("Abhay");function print(name) {
console.log("My name is " + name);
}

/*
The result of the code above is: "My name is Abhay"
*/

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
console.log(num); // Throws ReferenceError exception
num = 6; // Initialization
// 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

--

--

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store
Abhay Jain

Abhay Jain

Developer with 3 yrs of industrial experience in developing scalable web applications.