let, const & Temporal Dead Zone in JavaScript (Complete Guide)
In modern JavaScript, understanding how variables behave is extremely important. Earlier, developers mostly used var, but it often caused confusion due to its function scope and unpredictable behavior.
To solve these problems, JavaScript introduced let and const. These provide better control, reduce bugs, and make code more readable.
Variable lifecycle and scope in JavaScript
1. var vs let vs const
The keyword var has function scope, while let and const have block scope. This means let and const only exist inside the block where they are declared.
| Feature | var | let | const |
|---|---|---|---|
| Scope | Function | Block | Block |
| Hoisted | Yes | Yes | Yes |
| Initial Value | undefined | Not initialized | Not initialized |
| Access before declaration | Allowed | Error | Error |
| Reassignment | Allowed | Allowed | Not allowed |
2. Hoisting – What Actually Happens
Many developers say JavaScript moves variables to the top. Actually, JavaScript only allocates memory before execution begins.
It scans the entire code first and prepares memory. After that, it executes code line by line.
3. var Example
console.log(a); var a = 10;
JavaScript assigns undefined first, then updates the value later.
4. let Example
console.log(a); let a = 10;
Here, accessing the variable before initialization causes an error.
5. Temporal Dead Zone
TDZ is the time between variable creation and initialization. During this time, the variable cannot be accessed.
6. const Rules
const behaves like let but must be initialized immediately and cannot be reassigned.
const b = 20;
7. Block Scope
{
let x = 10;
}
console.log(x);
Conclusion
JavaScript prepares memory first and then executes code. Using let and const helps you write safer and cleaner code.
You now clearly understand modern JavaScript variables 🚀