var, let and const
var, let и const
JavaScript uses `var`, `let`, and `const` to declare variables. The keyword you choose controls where the name is visible and whether you can assign a new value to it.
Choose by scope and reassignment
Use const when a name should keep its initial value, and let when you intend to assign a new value later, as with a counter. Both are block-scoped: if you declare one inside an if block, you can use it in that block and its nested blocks, but not after the block ends. A regular const declaration needs an initializer. A let declaration can omit it, in which case the variable gets undefined when the declaration runs.
var is mostly encountered in older code. Inside a function, a var declaration belongs to the whole function, even if it appears inside a loop or conditional. You can reassign it, and repeating a var declaration for that name in the same scope normally doesn't create a second variable. In contrast, declaring the same name twice with let or const in one scope is a syntax error. A nested block can declare its own variable with the same name; this is called shadowing.
What happens before the declaration runs?
When a function starts, its local var bindings are already initialized to undefined. An initializer such as = 10 runs later, when execution reaches the declaration. This is one example of hoisting: the name is available before the line that declares it.
let and const bindings also exist from the start of their scope, but they are not initialized yet. Reading one before its declaration runs throws a ReferenceError. That interval is called the temporal dead zone (TDZ). If an inner declaration shadows an outer variable, a read in the TDZ does not fall back to the outer variable.
const does not freeze objects
For example, const settings = { darkMode: false } still lets you write settings.darkMode = true. You're changing a property of the same object. Writing settings = { darkMode: true } instead tries to make the name refer to a different object and throws a TypeError. The keyword protects the binding, not the contents of the value.
A common interview question
What does this code print, and what changes if var becomes let?
const callbacks = [];
for (var i = 0; i < 3; i++) {
callbacks.push(() => i);
}
console.log(callbacks.map(fn => fn())); // [3, 3, 3]
The callbacks don't save a copy of i when they're created. They read a shared variable when they're called, and by then the loop has ended with i equal to 3. With let in this loop header, each iteration gets its own binding, so the result is [0, 1, 2]. That's also why replacing var with let in existing code isn't always a mechanical edit: check both what closures capture and whether anything reads the variable outside the loop or block.