JavaScript Hoisting


In this tutorial you will learn about the hoisting behavior of JavaScript. JavaScript hoisting is a behavior in which variable and function declarations are moved to the top of their respective scopes during the compilation phase, before the code is executed. This means that variables and functions can be used before they are actually declared in the code.

For example, consider the following code:

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

In this code, the console.log statement will output undefined because the variable x is declared with the var keyword, which is hoisted to the top of the scope. However, the assignment x = 5 is not hoisted, so the value of x is undefined until it is assigned later in the code.

Similarly, function declarations are also hoisted to the top of their scope.

Example

foo(); // "TutorialsTrend!"
function foo() {
  console.log("TutorialsTrend!");
}

In this code, the function foo is declared and defined after it is called, but it still executes without error because the function declaration is hoisted to the top of the scope.

It's important to note that only the declarations are hoisted, not the assignments. So if a variable is declared and assigned in the same statement, only the declaration will be hoisted:

console.log(x); // Uncaught ReferenceError: x is not defined

To avoid confusion and potential errors, it's generally recommended to declare all variables and functions at the top of their respective scopes, regardless of whether or not they will be used later in the code.

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

Prev Next