Emmanuel Akinfulubi

TypeScriptBasic

let vs const vs var in TypeScript

2 let, const and var, and how they differ

easy

Declare one variable with each of let, const and var. Then show the two ways they differ: whether you can reassign them, and whether a block keeps them in.

Stuck? Three hints, smallest first
  1. 1. const stops you pointing the name at something else. It does not freeze an object’s contents.
  2. 2. let and const stop existing at the closing brace of their block. var leaks out to the whole function.
  3. 3. Put a var and a let inside an if block, then try to read both after it.

The answer, and proof it works

const same = (a: unknown, b: unknown): boolean =>
  JSON.stringify(a) === JSON.stringify(b);

function test(name: string, got: unknown, want: unknown): void {
  console.log(
    (same(got, want) ? 'ok   ' : 'FAIL ') + name +
    (same(got, want) ? '' : `  got ${JSON.stringify(got)}, want ${JSON.stringify(want)}`)
  );
}

function scoping(): string[] {
  const log: string[] = [];

  if (true) {
    var leaks = 'declared with var';
    let stays = 'declared with let';
    log.push('inside the block, both readable: ' + leaks + ' / ' + stays);
  }

  // `leaks` is still here, because var is scoped to the function.
  log.push('after the block, var is still readable: ' + leaks);

  // `stays` is gone. Uncommenting the next line is a compile error:
  // log.push(stays);   // Cannot find name 'stays'.
  return log;
}

let reassignable = 1;
reassignable = 2;                 // fine

const fixed = 1;
// fixed = 2;                     // error: Cannot assign to 'fixed'

// const protects the NAME, not the contents:
const settings = { theme: 'light' };
settings.theme = 'dark';          // allowed
console.log(settings.theme);

const lines = scoping();
for (const line of lines) console.log(line);

test('var escaped the block', lines.length, 2);
test('let was reassignable', reassignable, 2);
test('const object was still mutable', settings.theme, 'dark');

Output


      

Two separate ideas get confused here. Reassignment is about the name: const locks it. Scope is about where the name exists: let and const stop at the block, var runs to the end of the function. Use const by default, let when you must reassign, and var never.

Newsletter

New writing, when it lands.

Occasional notes on shipping software with AI agents. No schedule, no filler, unsubscribe in one click.