JavaScript Hoisting


JavaScript hoisting is a mechanism where variables and function declarations are moved to the top of their respective scopes before the execution of the code. This means that regardless of where variables and functions are declared in a JavaScript program, they are moved to the top of their respective scopes and are available for use throughout the entire scope.

Hoisting can be a confusing concept because it can lead to unexpected behavior if not understood properly. It's important to note that hoisting only applies to declarations, not initializations. In addition, let and const declarations are not hoisted in the same way as var declarations.

Therefore, it is best practice to declare and initialize variables and functions at the beginning of their respective scopes to avoid any unexpected behavior.


1. Function Hoisting

Function hoisting is a mechanism in JavaScript that allows function declarations to be moved to the top of their scope before the execution of the code. This means that functions can be called before they are declared in the code. To avoid any unexpected behaviour, it is best practice to declare and define functions at the beginning of their respective scopes.

Example

Preview

2. Variable Hoisting

Variable hoisting is a mechanism in JavaScript that allows variables to be declared at any point in the code, but are moved to the top of their scope before the execution of the code. This means that variables can be used before they are declared, but their values will be undefined until they are actually assigned a value. To avoid any unexpected behaviour, it is best practice to declare and define variables at the beginning of their respective scopes.

The variable declarations are similarly automatically raised to the top of their current scope. The variable will be moved to the top of the function if it is declared inside a function block, but if it is defined outside of any function, it will be moved to the top of the script and become globally accessible.

Example

Preview