How variables are declared dictates their scope, visibility, and reassignment rules in JavaScript. Since ES6, developers have three options: var, let, and const.
Summary Comparison Table
| Feature | var | let | const |
|---|---|---|---|
| Scope | Function Scope | Block Scope | Block Scope |
| Hoisted | Yes (initialized to undefined) | Yes (uninitialized / TDZ) | Yes (uninitialized / TDZ) |
| Reassigned | Yes | Yes | No |
| Redeclared | Yes | No | No |
Scope Examples
// var is function scope
if (true) {
var x = 5;
}
console.log(x); // 5
// let & const are block scope
if (true) {
let y = 10;
}
console.log(y); // ReferenceError: y is not defined