JavaScript Hoisting Explained

JavaScript Logo

Hoisting is a JavaScript mechanism where variable and function declarations are moved to the top of their containing scope before code execution. It's important to understand that only the declarations are hoisted, not the initializations.

Variable Hoisting

Variables declared with `var` are hoisted and initialized with `undefined`. This means you can access them before they are declared without getting a `ReferenceError`, but their value will be `undefined`.

console.log(myVar); // Output: undefined
var myVar = 5;
console.log(myVar); // Output: 5

`let` and `const` Hoisting: Variables declared with `let` and `const` are also hoisted, but they are not initialized. Accessing them before the declaration results in a `ReferenceError`. This is known as the Temporal Dead Zone (TDZ).

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

Function Hoisting

Function declarations are fully hoisted, meaning you can call a function before you declare it in the code.

sayHello(); // Output: 'Hello!'

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

However, function expressions (where a function is assigned to a variable) are not hoisted in the same way. The variable declaration is hoisted, but the function body is not.

// sayGoodbye(); // Throws TypeError: sayGoodbye is not a function

var sayGoodbye = function() {
  console.log('Goodbye!');
};

Best Practice: To avoid confusion, always declare your variables and functions at the top of their scope, especially when using `var`.

Comments