JavaScript | Hoisting

25 May, 2022
In JavaScript, Hoisting is the default behavior of moving all the declarations at the top of the scope before code execution. Basically, it gives us an advantage that no matter where functions and variables are declared, they are moved to the top of their scope regardless of whether their scope is global or local. 
It allows us to call functions before even writing them in our code. 
Note: JavaScript only hoists declarations, not the initializations.
JavaScript allocates memory for all variables and functions defined in the program before execution.
Let us understand what exactly this is: The following is the sequence in which variable declaration and initialization occur. 
Declaration –> Initialisation/Assignment –> Usage 
// Variable lifecycle
let a;        // Declaration
a = 100;      // Assignment
console.log(a);  // Usage
However, since JavaScript allows us to both declare and initialize our variables simultaneously, this is the most used pattern:  
let a = 100;
Note: Always remember that in the background the Javascript is first declaring the variable and then initializing them. It is also good to know that variable declarations are processed before any code is executed. 
However, in javascript, undeclared variables do not exist until code assigning them is executed. Therefore, assigning a value to an undeclared variable implicitly creates it as a global variable when the assignment is executed. This means that all undeclared variables are global variables.
Javascript
// hoistingfunction codeHoist(){    a = 10;    let b = 50;}codeHoist(); console.log(a); // 10console.log(b); // ReferenceError : b is not defined
Output: 
Explanation: In the above code sample we created a function called codeHoist() and in there we have a variable which we didn’t declare using let/var/const and a let variable b. The undeclared variable is assigned the global scope by javascript hence we are able to print it outside the function, but in case of the variable b the scope is confined and it is not available outside and we get a ReferenceError.
Note: There’s a difference between ReferenceError and undefined error. An undefined error occurs when we have a variable that is either not defined or explicitly defined as type undefined. ReferenceError is thrown when trying to access a previously undeclared variable. 
ES5
When we talk about ES5, the variable that comes into our minds is var. Hoisting with var is somewhat different as when compared to let/const. Let’s make use of var and see how hoisting works:  
Javascript
// var code (global)console.log(name); // undefinedvar name = 'Mukul Latiyan';
Output: 
Explanation: In the above code we tried to console the variable name which was declared and assigned later than using it, the compiler gives us undefined which we didn’t expect as we should have got ReferenceError as we were trying to use name variable even before declaring it. 
But the interpreter sees this differently, the above code is seen like this:  
Javascript
//how interpreter sees the above codevar name;console.log(name); // undefinedname = 'Mukul Latiyan';
Output: 
Function scoped variable
Let’s look at how function scoped variables are hoisted.  
Javascript
//function scopedfunction fun(){    console.log(name);    var name = 'Mukul Latiyan';}fun(); // undefined
Output: 
There is no difference here as when compared to the code where we declared the variable globally, we get undefined as the code seen by the interpreter is: 
Javascript
//function scopedfunction fun(){    var name;    console.log(name);    name = 'Mukul Latiyan';}fun(); // undefined
Output: 
In order to avoid this pitfall, we can make sure to declare and assign the variable at the same time, before using it. Something like this:  
Javascript
//in order to avoid itfunction fun(){    var name = 'Mukul Latiyan';    console.log(name); // Mukul Latiyan}fun();
Output: 
ES6
Let We know that variables declared with let keywords are block scoped not function scoped and hence it is not any kind of problem when it comes to hoisting. 
Example:  
Javascript
//let example(global)console.log(name);let name='Mukul Latiyan'; // ReferenceError: name is not defined
Output: 
Like before, for the var keyword, we expect the output of the log to be undefined. However, since the es6 let doesn’t take kindly on us using undeclared variables, the interpreter explicitly spits out a Reference error. This ensures that we always declare our variable first. 
const behaves similar to let when it comes to hoisting. 
immukul
Akanksha_Rai
kbhattacharyya88
sweetyty
surinderdawra388
javascript-basics
JavaScript
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
File uploading in React.js
Hide or show elements in HTML using display property
How to Open URL in New Tab using JavaScript ?
Node.js | fs.writeFileSync() Method
How do you run JavaScript script through the Terminal?
JavaScript | console.log() with Examples
How to append HTML code to a div using JavaScript ?
JavaScript String includes() Method
Send unlimited Whatsapp messages using JavaScript
Set the value of an input field in JavaScript