π Introduction
Have you ever encountered an error like undefined is not a function or wondered why a variable seems to exist before it's declared?
Welcome to the quirky world of hoisting in JavaScript β a concept that surprises most developers when they first see it in action.
In this blog post, you'll learn:
- What is hoisting in JavaScript?
- How variables and functions are hoisted
- The difference between var, let, and const
- Real examples and a mental model to remember hoisting
π What is Hoisting?
Hoisting is JavaScriptβs default behavior of moving declarations to the top of the current scope (function or global).
This means you can use variables and functions before you declare them β but thereβs a catch!
π Example 1: Variable Hoisting with var
console.log(name); // undefined
var name = "Ankur";
Explanation:
The variable name
is hoisted, but only the declaration (not the value) is moved to the top.Itβs as if you wrote:
var name;
console.log(name); // undefined
name = "Ankur";
π« What about let
and const
?
console.log(age); // β ReferenceError
let age = 25;
Variables declared with let
and const
are not initialized during hoisting.
They remain in a Temporal Dead Zone (TDZ) until the line of declaration is reached.
π Example 2: Function Hoisting
greet();
function greet() {
console.log("Hello there!");
}
β
This works!
Function declarations are hoisted with their definitions.
β οΈ Function Expressions are NOT Hoisted
sayHi(); // β TypeError
var sayHi = function () {
console.log("Hi!");
};
π§ Visual Model of Hoisting
π Summary
Concept | Hoisted? | Accessible before declaration? |
---|---|---|
var |
β Yes | β οΈ Yes, but value is undefined |
let / const
|
β Yes | β No, in TDZ |
Function Declaration | β Yes | β Yes |
Function Expression | β No | β No |
π¬ Final Thoughts
Understanding hoisting helps prevent bugs and write cleaner JavaScript code.
Next time you write a function or a variable, remember this internal "lift" that JavaScript performs.
π Read Full Blog with Code and Visuals
π https://webcodingwithankur.blogspot.com/2025/06/what-is-hoisting-in-javascript.html
Top comments (2)
A function expression using
var
is hoisted.When you write:
Itβs as if you wrote:
And if you use
let
orconst
you get aReferenceError
.And the behavior is the same if you use "classic" or "arrow" functions.
so , you mean that i have written wrong something in this post.