typescript

When to Use let vs const in TypeScript

Use const by default. Use let when you need to reassign.

16 May 2024

Use const by default. Use let when you need to reassign.

That's it. That's the rule.

const doesn't mean immutable

This trips people up. const prevents reassignment, not mutation. You can't point the variable at something else. But if it points to an object or array, you can still change the contents.

Typescript
const PI = 3.14;
PI = 3.14159; // Error: Assignment to constant variable.

const numbers = [1, 2, 3];
numbers.push(4); // works fine
console.log(numbers); // [1, 2, 3, 4]

numbers still points to the same array. You just changed what's inside it. const doesn't care.

let is for values that change

Use let when you know the variable will be reassigned. Loop counters, accumulators, state that changes over time.

Typescript
let counter = 0;
if (true) {
  let counter = 1;
  console.log(counter); // 1
}
console.log(counter); // 0

Both let and const are block-scoped. The counter inside the if block is a different variable than the one outside.

Why const by default

Dave Herman put it well: "Using const is a powerful way to signal your intent and reduce the cognitive load on readers of your code."

When I read const, I know this binding won't change. I can stop tracking it. When I read let, I know to watch for reassignment somewhere below. That signal matters in a 500-line file.

The trade-off

const by default makes code easier to reason about. You see let and immediately know something will change.

The cost: it's a convention, not enforcement. const on an object doesn't prevent deep mutation. If you need true immutability, you need Object.freeze(), as const, or an immutable data library. const alone won't protect you.

Keep reading