2 min read

Hoisting

Hoisting is a JavaScript mechanism where variables and function declarations are moved to the top of their scope before code execution. In reality, the JavaScript engine scans the code before executing it, allocates memory for variables and functions, and this gives the appearance of "hoisting".

1. Variable Hoisting

var

Variables declared with var are hoisted and initialized with undefined.

console.log(x); // undefined (no error)
var x = 5;
console.log(x); // 5

let and const

Variables declared with let and const are also hoisted, but they are not initialized. Accessing them before the declaration results in a ReferenceError. This period between the start of the scope and the declaration is called the Temporal Dead Zone (TDZ).

console.log(y); // ReferenceError: Cannot access 'y' before initialization
let y = 10;

2. Function Hoisting

Function Declarations

Function declarations are fully hoisted. You can call the function before it is defined in the code.

sayHello(); // "Hello!"

function sayHello() {
  console.log("Hello!");
}

Function Expressions

Function expressions (including arrow functions) are treated as variables. If assigned to a var, they are hoisted as undefined. If assigned to let or const, they fall into the TDZ.

sayHi(); // TypeError: sayHi is not a function

var sayHi = function() {
  console.log("Hi!");
};

3. Best Practices

  1. Declare variables at the top: To avoid confusion, declare variables at the beginning of their scope.
  2. Use let and const: They enforce cleaner scoping rules and prevent accidental usage before initialization.
  3. Declare functions before calling them: While hoisting allows otherwise, defining functions first improves readability.

programming/javascript/vanilla/javascript programming/functions-and-scope