JavaScript Hoisting

JavaScript hoisting is a concept that describes how variables and functions are processed by the JavaScript interpreter during runtime. It is a process that occurs before the code is executed, and it allows the interpreter to move all variable and function declarations to the top of the scope.

Why should you use it?

  • It allows you to use variables and functions before they are declared in the code.
  • It helps to avoid errors related to undeclared variables.
  • It helps to make code more readable and maintainable.

Hoisting

Hoisting is a JavaScript mechanism where variables and function declarations are moved to the top of their scope before code execution. 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.

In JavaScript, all declarations (variable, function, const, let, etc.) are hoisted to the top of the scope, whether it’s the global scope or a function scope. In other words, all declarations are processed before any code is executed.

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).

In JavaScript, there are two types of declarations:

  • Variable declarations
  • Function declarations

Variable Declarations

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.

In JavaScript, a variable declaration is hoisted to the top of the current scope. This means that a variable can be declared after it has been used.

For example:

console.log(foo);
var foo = 'bar';

The above code will output:

foo is not defined

This is because the variable declaration is hoisted to the top of the scope, which means that the variable is declared before the code is executed.

However, the variable assignment (foo = 'bar') is not hoisted. This means that the variable must be declared before it can be assigned a value.

Function Declarations

In JavaScript, a function declaration is hoisted to the top of the current scope. This means that a function can be declared after it has been used.

For example:

foo();
function foo() {
  console.log('foo');
}

The above code will output:

foo

This is because the function declaration is hoisted to the top of the scope, which means that the function is declared before the code is executed.

However, the function expression (const foo = function() { ... }) is not hoisted. This means that the function must be declared before it can be used.

1