Hoisting in JavaScript

What is Hoisting?

Hoisting is when the JavaScript interpreter moves all variable and function declarations to the top of the current scope.

Hoisting is done during the interpreter’s first run through the code.

The important thing is that the actual declarations are hoisted, and that assignments will be left where they are.

Hoisting is a JS mechanism where variables and functions are declarations are moved to the top before code execution.

All functions and variables that are declared are moved to the top of their scope regardless of whether their scope is global or local.

Of note however, is the fact that the hoisting mechanism only moves the declaration. The assignments are left in place.

Variable declarations are one of the most common aspects of any programming language.

However, JavaScript has a little quirk, known as hoisting, which can turn an innocent declaration into a subtle bug.

The variable and function declarations are put into memory during the compile phase ,  and a hoisting suggests that variable and function declarations are moved to the top of code..

Always Declare Variables At the Top !Hoisting is (to many developers) an unknown or overlooked behavior of JavaScript.

To avoid bugs, always declare all variables at the beginning of every scope.

Example

Variable Declarations

This is a basic example:

Function Declarations

Hoisting also applies to function declarations.

This is a basic example:

Function Hoisting

Function declarations are also be hoisted. But that functions, what assigned to variables, that’s are not hoisted.

For example, the following code will work due to function declaration hoisting.

The variable declaration for foo is hoisted before the function call.

However, since the assignment to bar is not hoisted, an exception is thrown for trying to call a non-function variable.

Conclusion

Hoisting is an easy to understand, but often overlooked nuance.

To help avoid these bugs, many developers advocate for a single variable declaration statement at the very beginning of every scope.

Hoisting is JS’s default behavior of moving declarations to the top.

JavaScript Declarations are Hoisted

In JS, a variable can be declared after it has been used.

A variable can be used before it has been declared.

Example 1 does not give the same result as Example 2:

Example 1

Output

Example 2