let and const in TypeScript
Using let
Use let when a variable's value genuinely needs to change later in the program, such as a loop counter or an accumulator that's updated over time. TypeScript will still enforce the variable's declared or inferred type on every reassignment.
Example: Using let
let counter: number = 0;
for (let i = 0; i < 3; i++) {
counter += i;
}
console.log(counter);
Using const
Use const when a variable should never be reassigned after it's initialized, which is the recommended default for most variables in modern TypeScript. Note that const only prevents reassignment of the variable itself, not mutation of an object or array it points to.
Example: Using const
const maxUsers: number = 100;
console.log(maxUsers);
Block Scope
Both let and const are block-scoped, meaning they only exist and are accessible inside the specific block, like an if statement or loop body, where they're declared. This is a deliberate improvement over the older var keyword, which is scoped to the entire function instead.
Example: Block Scope
if (true) {
let blockScoped = "inside";
console.log(blockScoped);
}
// console.log(blockScoped); // rejected: not accessible here
Changing Variable Values
A let variable can be reassigned freely as many times as needed throughout its scope, while a const variable throws a compile error the moment you try to reassign it. This distinction is what makes const a useful signal to readers that a value is meant to stay fixed.
Example: Changing Variable Values
let score: number = 10;
score = 20;
console.log(score);
const maxScore: number = 100;
// maxScore = 200; // rejected: cannot reassign a const
Choosing let or const
Prefer const by default whenever a variable doesn't need reassignment, since it communicates intent clearly and prevents accidental overwrites. Reach for let only in the specific cases, like counters or state that's reassigned over time, where reassignment is actually required.
Example: Choosing let or const
const PI = 3.14; // never reassigned
let radius = 5; // will change below
radius = 10;
console.log(PI * radius * radius);
Chapter Quiz — Complete all 10 topics to unlock
0/10 topics done
Complete these topics first: