WEB DEVELOPER SITE
HTMLCSSJAVASCRIPTSQLPHPBOOTSTRAPJQUERYANGULARXML
 

JavaScript Hoisting


In JavaScript, function and variable declarations are promoted to the top of the function.

In JavaScript, variables can be declared after they are used, that is, variables can be used before being declared.

The following two examples will achieve the same result:

Example 1 gives indistinguishable outcome from Example 2:

Example 1

x = 5; // variable x is set to 5 elem = document.getElementById ("demo"); // find element elem.innerHTML = x; // display x in the element var x; // declare x
Try it yourself »

Example 2

var x; // declare x x = 5; // variable x is set to 5 elem = document.getElementById ("demo"); // find element elem.innerHTML = x; // display x in the element
Try it yourself »

To understand the above example, you need to understand "hoisting".

Variable promotion: Function declarations and variable declarations are always silently "promoted" to the top of the method body by the interpreter.


JavaScript initialization does not improve

JavaScript only promotes declared variables, not initialized ones.

The following two examples have different results:

Example 1

var x = 5; // initialize x var y = 7; // initialize y elem = document.getElementById ("demo"); // find element elem.innerHTML = x + "" + y; // show x and y
Try it yourself »

Example 2

var x = 5; // initialize x elem = document.getElementById ("demo"); // find element elem.innerHTML = x + "" + y; // show x and y var y = 7; // initialize y
Try it yourself »

Does it bode well that y is unclear in the last example?

This is on the grounds that just the affirmation (var y), not the instatement (=7) is raised to the top.

Because of raising, y has been proclaimed before it is utilized, but since instatements are not raised, the estimation of y is undefined.

Example 2 is equivalent to writing:

Example

var x = 5;/Initialize x
var y;    /Declare y

elem = document.getElementById("demo");/Find a component
elem.innerHTML = x + " " + y;           //Display x and y

y = 7;   /Assign 7 to y
Try it yourself »

Declare Your Variables At the Top !

For most programmers, JavaScript hoisting is unknown.

If programmers don't understand hoisting well, the programs they write are prone to problems.

To avoid these problems, we usually declare these variables before the beginning of each scope. This is also a normal JavaScript parsing step, which is easy for us to understand.

Note JavaScript strict mode does not allow the use of undeclared variables.
In the next chapter we will learn "strict mode" .