×

Index

JavaScript Tutorial

JavaScript Examples

CSS Tutorial

CSS Examples

Hoisting in JavaScript

JavaScript Hoisting: In this tutorial, we will learn about an uncommon feature of JavaScript that is Hoisting with the help of examples. By Siddhant Verma Last updated : July 29, 2023

JavaScript Hoisting

An uncommon feature of JavaScript that junior devs and people who have just started learning JavaScript tend to ignore is Hoisting. Before ES6, variables in JavaScript were only declared with the var keyword and all the declarations were placed at the top. This means that if you do something like this you won't get an error,

JavaScript Hoisting Example 1

x=5;
console.log(x);
var x;

You will get 5 displayed on the console. If you've worked with languages like C/C++ you might find it strange. In such languages, you can expect an error saying something like x is not defined because compiler reads from top to bottom. So is JavaScript also executed from top to bottom? Well, if it were, you wouldn't be able to do this. Then how come we can use a variable and declare it later? The answer is Hoisting. Hoisting means moving all declarations to the top. This means that while executing the code, all variable declarations are on the top so till the time you come to x=5 line you already know that x has been declared a variable somewhere in the program.

JavaScript Hoisting Example 2

Let's see another example,

y=3;
function setRandom(y){
 	console.log('Before declaring y: ' ,y);
}
var y;
console.log('After declaring y: ',y);

Hoisting is JavaScript's default behavior. If someone is unfamiliar with this concept, it may introduce bugs into the program. Hence best practice is to declare all the variables at the top.

The Catch

Let's modify the first example a bit,

console.log(x);			//Undefined
var x=5;

Hoisting strictly says that only variable declarations are hoisted and not initializations. Hence you will get undefined because Js read your code from the top and x was not hoisted so it had no meaning when your program reached the console.log() statement.

After ES6, two ways of declaring a variable were introduced- let and const.

If you wish to know more about them, check out the article of Variables in JavaScript.

let and const are not hoisted. This means that if you use let instead of var in the above example you'll get "undefined". In reality, let is hoisted in a TDZ( temporal dead zone). A zone where you can't use variables that have not been defined.

Note: if you are using strict mode in your JavaScript then you're more likely to run into getting "undefined" values for such types of code because strict mode does not allow any hoisting to take place.

JavaScript Tutorial »



Comments and Discussions!

Load comments ↻





Copyright © 2024 www.includehelp.com. All rights reserved.