JS Hoisting Behavior

In this tutorial you will learn about the hoisting behavior of JavaScript.
 

What is Hoisting

In JavaScript, all variable and function  declarations are moved or hoisted to the top of their current scope, regardless of where it is defined. This is the default behavior of JavaScript interpreter which is called hoisting. In the tutorial we'll take a closer look on hoisting.
 

Function Hoisting

In JavaScript, functions that are defined using a function declaration method are automatically hoisted. So, they can be invoked before they are defined. Let's understand it from the example below:

// Calling function before declaration
sayHello(); // Outputs: Hello, I'm hoisted!

function sayHello() {
    alert("Hello, I'm hoisted!");
}

From the example above, we have called the sayHello() function before it is defined, but the code still works. This is because the function declaration is hoisted to the top automatically behind the scenes.


Variable Hoisting

The variable declarations just like the function declaration, are also hoisted to the top of their current scope automatically. That is. when the variable is declared inside a function block, it will be moved to the top of the function, however, if it is declared outside any function it will be moved to the top of the script and become globally available. The example below will show us how this works:

str = "Hello World!";
alert(str); // Outputs: Hello World!
var str;

The JavaScript only hoists declarations, not initializations. This is to say that when a variable is declared and initialized after using it, the value will be undefined. Take a look at this example:

alert(str); // Outputs: undefined
var str;
str = "Hello World!";

Below is another example illustrating the variable hoisting behavior of JavaScript:

var i = 1; // Declare and initialize i
alert(i + ", " + j); // Outputs: 1, undefined
var j = 2; // Declare and initialize j

var x = 5; // Declare and initialize x
var y; // Declare y
alert(x + ", " + y); // Outputs: 5, undefined
y = 10; // Initialize y

var a = 3; // Declare and initialize a
b = 6; // Initialize b
alert(a + ", " + b); // Outputs: 3, 6
var b; // Declare b

var u = 4; // Declare and initialize u
alert(u + ", " + v); // Outputs: 4, undefined
var v; // Declare v
v = 8; // Initialize v

Though variable hoisting may seem a little bit confusing at first glance, if you go through these examples carefully you will easily understand how it works.

Note: It is best practice to declare your variables at the top of the current scope, because of the behavior of hoisting. However, in JavaScript, using a variable without declaring is not allowed (strict mode).  check the next tutorial on Strict Mode to learn more.