JavaScript Hoisting

JavaScript Hoisting

JavaScript uses hoisting to lift declarations to the top.

Many developers are unfamiliar with the hoisting behavior of JavaScript, which can cause bugs (errors) in programs. To avoid bugs, you should always declare all variables at the beginning of every scope. Because JavaScript interprets the code in this fashion and it is always a favorable tactic.

Let's give an example

Example 1

x = 3; // Assign 3 to x

element = document.getElementById("example");
element.innerHTML = x;                     // Display x in the element

var x; // Declare x

Example 2

var x; // Declare x
x = 3; // Assign 3 to x

element = document.getElementById("demo");
element.innerHTML = x;

Note: Variables cannot be used in JavaScript unless they are explicitly declared and Javascript can not be used to hoist initializations only declarations