What is hoisting in JavaScript

Hoisting is a JavaScript mechanism where variable and function declarations are moved to the top of their scope (either the global scope or the function scope) during the compilation phase. This means you can use variables and functions before they are declared in the code.

However, only the declarations are hoisted, not the initializations. Let’s break down how this works for var, let, const, and functions.

1. Hoisting with var

  • When you declare a variable with var, JavaScript hoists the declaration to the top, but the initialization remains in place.
  • This results in the variable being accessible before its declaration but with an initial value of undefined.

Example:

console.log(myVar); // Output: undefined (hoisted declaration, but not initialization)
var myVar = 5;
console.log(myVar); // Output: 5

Here, myVar is hoisted to the top and given a default value of undefined until it is assigned 5.

2. Hoisting with let and const

  • Variables declared with let and const are also hoisted, but they are not initialized. They exist in a “temporal dead zone” from the start of the block until the line where they are declared.
  • Accessing them before their declaration results in a ReferenceError.

Example:

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

For const:

console.log(myConst); // ReferenceError: Cannot access 'myConst' before initialization
const myConst = 15;

3. Hoisting with Functions

  • Function Declarations (e.g., function myFunc() { ... }) are fully hoisted, meaning both the function name and its body are hoisted. You can call the function before it’s defined in the code.

Example:

myFunc(); // Works because function is fully hoisted
function myFunc() {
    console.log("Hello, world!");
}
  • Function Expressions (e.g., const myFunc = function() { ... }) are not fully hoisted. Only the variable declaration is hoisted, not the assignment. If you try to call the function before the line where it’s defined, you’ll get an error.

Example:

myFunc(); // TypeError: myFunc is not a function
const myFunc = function() {
    console.log("Hello, world!");
};

Summary of Hoisting

TypeHoisted DeclarationHoisted InitializationAccessible Before Declaration
varYesNo (initially undefined)Yes, but undefined
let and constYesNoNo (causes ReferenceError)
Function DeclarationsYesYesYes
Function ExpressionsOnly declarationNoNo (causes TypeError)

Hoisting helps JavaScript interpret code, even if variables and functions are not declared at the top of their scope. However, being aware of this behavior can help prevent confusing bugs.

Leave a Reply

Your email address will not be published. Required fields are marked *