0
0
JavascriptConceptBeginner · 3 min read

What is Hoisting in JavaScript: Explanation and Examples

In JavaScript, hoisting is a behavior where variable and function declarations are moved to the top of their containing scope before code execution. This means you can use functions and variables before they are declared in the code.
⚙️

How It Works

Imagine you are packing for a trip and you put all your clothes on the top of your suitcase before adding other items. In JavaScript, hoisting works similarly by moving all variable and function declarations to the top of their scope before the code runs. This means the JavaScript engine reads and sets up these declarations first, even if they appear later in the code.

However, only the declarations are hoisted, not the assignments. So if you declare a variable and assign a value later, the variable is known early but its value is undefined until the assignment line runs. Functions declared with the function keyword are fully hoisted, so you can call them before their actual place in the code.

💻

Example

This example shows how a function and a variable behave with hoisting. The function can be called before it is declared, but the variable is undefined until assigned.

javascript
console.log(greet());

function greet() {
  return 'Hello!';
}

console.log(message);
var message = 'Hi there!';
console.log(message);
Output
Hello! undefined Hi there!
🎯

When to Use

Understanding hoisting helps you avoid bugs caused by using variables or functions before they are ready. It is useful when organizing code so you know which declarations are available at any point. For example, you can safely call functions before their declaration, which can make your code cleaner.

However, relying too much on hoisting can make code harder to read. It's best to declare variables and functions before using them to keep code clear and predictable.

Key Points

  • Hoisting moves declarations, not assignments, to the top of their scope.
  • Function declarations are fully hoisted and can be called before they appear.
  • Variables declared with var are hoisted but initialized as undefined until assigned.
  • let and const are hoisted differently and cause errors if used before declaration.
  • Understanding hoisting helps prevent unexpected bugs and improves code clarity.

Key Takeaways

Hoisting moves variable and function declarations to the top before code runs.
Function declarations can be used before they appear in the code.
Variables declared with var are hoisted but start as undefined until assigned.
Avoid using variables before declaration to keep code clear and bug-free.
Let and const behave differently and are not accessible before declaration.