What is Hoisting in JavaScript?
Hoisting is a fundamental JavaScript concept where variable and function declarations are moved to the top of their scope during compilation. While it might seem like declarations are physically "lifted," JavaScript actually processes them before executing the code.
How Hoisting Works
1. Variable Hoisting
var
: Hoisted and initialized withundefined
.console.log(x); // undefined (not an error) var x = 5;
let
/const
: Hoisted but not initialized (Temporal Dead Zone).console.log(y); // ReferenceError let y = 10;
2. Function Hoisting
- Function declarations are fully hoisted:
greet(); // "Hello!" (works) function greet() { console.log("Hello!"); }
- Function expressions (using
var
/let
/const
) follow variable hoisting rules.
Why Hoisting Matters
- Avoid bugs by understanding scope and initialization.
- Know why
let
/const
are safer thanvar
. - Debug "undefined" vs. "ReferenceError" issues.
Best Practices
✔ Use let
/const
over var
.
✔ Declare variables at the top of their scope.
✔ Always initialize variables before use.
At Online Learner, we're on a mission to ignite a passion for learning and empower individuals to reach their full potential. Founded by a team of dedicated educators and industry experts, our platform is designed to provide accessible and engaging educational resources for learners of all ages and backgrounds.
Terms Disclaimer About Us Contact Us
Copyright 2023-2025 © All rights reserved.