Hoisting in JS

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

--

--

--

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

Love podcasts or audiobooks? Learn on the go with our new app.

Recommended from Medium

Saga Poshtel Oslo Central

Closures in JavaScript

My Best Friend — Building an App using a Design System and Dog API

Event Loop in JavaScript

A Practical Introduction to TypeScript Class Decorators

Simplifying Angular Unit Testing

Implementing Routes with React Router DOM

Lightning Web Component v/s Aura v/s Flow with an Example

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.

More from Medium

Special Concepts about JavaScript & MongoDB

The Good HTML Component

A quick guide for passing props using navigation and UseLocation hook in react-router-dom

My Journey Into The JavaScript Abyss