Declare a binding with the right reassignment rule
Use const when a binding should not be reassigned and let when it must change. Both are block-scoped. var has function scope or a global-scope behavior that differs from block-scoped declarations, and its redeclaration rules can hide mistakes in older code.
const course = 'JavaScript';
let completed = 0;
completed += 1;
console.log(course, completed); // JavaScript 1
if (true) {
let inside = 'block only';
var older = 'function or global scope';
}
console.log(older);
// console.log(inside); // ReferenceErrorconst does not freeze an object
const student = { name: 'Asha', score: 0 };
student.score = 10; // permitted: the object changes
console.log(student.score); // 10
// student = {}; // TypeError: binding reassignmentThe binding still points to the same object. Object mutation and binding reassignment are separate operations. Object.freeze can restrict an object's own properties, but it is shallow and not a general deep-immutability mechanism.
Initialization and the temporal dead zone
A let or const binding cannot be used before its initialization point in the scope. Reading it earlier throws a ReferenceError. A var declaration is initialized to undefined before its assignment executes, which can allow a mistake to travel farther before failing. Do not describe this difference merely as “let is not hoisted”; declaration processing and initialization are distinct.
Scope in a loop
A for loop with let can create separate per-iteration bindings, useful when callbacks remember the loop variable. A var loop uses one binding in its containing scope. The closures chapter explores this with runnable examples.
Practice with answers
- Use const for a fixed course label and let for a changing question index.
- Attempt to reassign the label and read the error.
- Predict
console.log(x); var x = 3;: undefined, before the assignment. - Predict a read before
let y = 3;in the same scope: ReferenceError.
हिन्दी संकेत: const variable binding को दोबारा assign नहीं होने देता; उसके object की properties अपने आप immutable नहीं बनतीं।