var vs let vs const
The three ways to declare variables in JavaScript. Understanding their differences in scope, hoisting, and reassignment is fundamental to writing modern JS.
| Feature | var | let | const |
|---|---|---|---|
| Scope | Function-scoped | Block-scoped | Block-scoped |
| Hoisting | Hoisted and initialized to undefined | Hoisted but not initialized (TDZ) | Hoisted but not initialized (TDZ) |
| When to use | Never (legacy code only) | When the value needs to change | Default choice for all declarations |
| Reassignment | Yes | Yes | No |
| Redeclaration | Yes (in same scope) | No (in same scope) | No (in same scope) |
| Temporal Dead Zone | No | Yes | Yes |
Verdict
Use const by default. Use let only when you need to reassign. Never use var in modern code.
Code Example
Related Tutorials
Related Glossary Terms
A named container that stores a value in memory. JavaScript uses let, const, and var to declare variables. let and const are block-scoped, while var is function-scoped.
HoistingJavaScript's behavior of moving variable and function declarations to the top of their scope before code execution. var declarations are hoisted and initialized to undefined, while let and const are hoisted but not initialized (temporal dead zone).
ScopeThe region of code where a variable is accessible. JavaScript has global scope, function scope, and block scope. Block scope was introduced with let and const in ES6.
Const vs Let vs Varconst declares a block-scoped, read-only reference (the value itself can still be mutated for objects/arrays). let declares a block-scoped, reassignable variable. var declares a function-scoped, hoisted variable. Prefer const by default, let when reassignment is needed, avoid var.