Hoisting is JavaScript's default behavior of moving declarations to the top.
In JavaScript, a variable can be declared after it has been used. In other words; a variable can be used before it has been declared.
Let's take a look at the examples below.
//Example 1
x = 5; // Assign 5 to x
elem = document.getElementById("demo"); // Find an element
elem.innerHTML = x; // Display x in the element
var x; // Declare x
In the example above we are declaring the variable after assigning value and even using it. The following example gives same result as well when you declare the variable first and then use it.
//Example 2
var x; // Declare x
x = 5; // Assign 5 to x
elem = document.getElementById("demo"); // Find an element
elem.innerHTML = x; // Display x in the element
As I have mentioned earlier, Hoisting is JavaScript's default behavior of moving all declarations to the top of the current scope (to the top of the current script or the current function).
Variables and constants declared with let or const are not hoisted!
JavaScript Initializations are Not Hoisted either!
//Example 3
var x = 5; // Initialize x
var y = 7; // Initialize y
elem = document.getElementById("demo"); // Find an element
elem.innerHTML = x + " " + y; // Display x and y
//Example 4
var x = 5; // Initialize x
elem = document.getElementById("demo"); // Find an element
elem.innerHTML = x + " " + y; // Display x and y
var y = 7; // Initialize y
We need to declare your variables at the top! Why? Because Hoisting is an unknown or overlooked behavior of JavaScript. If we, as developers, don't understand hoisting, programs may contain errors. To avoid any types of bugs and errors, it's a great practice to declare all variables at the beginning of every scope. Since this is how JavaScript interprets the code, it is always a good rule to follow.
Hoisting