← Back to TypeScript Course | Chapter 3: Variables and Functions | Lesson 1 of 10

let and const in TypeScript

TypeScript uses JavaScript's let and const declarations for creating variables. The main difference is that let allows reassignment, while const prevents reassignment after initialization.

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

typescript
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

typescript
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

typescript
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

typescript
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

typescript
const PI = 3.14; // never reassigned
let radius = 5;   // will change below
radius = 10;
console.log(PI * radius * radius);

Login to run this code

C/C++/Java/PHP execution requires a free account. Your code is saved — you'll land right back in the editor after logging in.