Emmanuel Akinfulubi

JavaScriptFundamental (ES6), part 1

let vs const vs var in JavaScript

1 let, const and var in a block

easy

Declare the same name three ways inside a function, shadow each one inside an if block, and report which of the three the block actually changed.

Stuck? Three hints, smallest first
  1. 1. var is scoped to the whole function. let and const are scoped to the nearest pair of braces.
  2. 2. So a second var x inside the block is the same variable; a second let x is a new one.
  3. 3. Reading a name that was never declared throws, but typeof on it does not.

The answer

function shadow() {
  var loose = 'outer';
  let scoped = 'outer';
  const fixed = 'outer';
  if (true) {
    var loose = 'inner';        // the SAME variable, reassigned
    let scoped = 'inner';       // a NEW variable, dead at the closing brace
    const fixed = 'inner';
  }
  return { loose, scoped, fixed };
}

function afterTheBlock() {
  if (true) {
    var kept = 'still here';
    let dropped = 'gone at the brace';
  }
  let seen;
  try { seen = dropped; } catch (e) { seen = e.constructor.name; }
  return { kept, seen };
}

const rebind = (() => {
  const rate = 1;
  try { rate = 2; return 'allowed'; } catch (e) { return e.constructor.name; }
})();

console.log('shadow()         :', shadow());
console.log('afterTheBlock()  :', afterTheBlock());
console.log('reassigning const:', rebind);
console.log('typeof a name nobody declared:', typeof neverDeclared, '<- no error');

Output


      
7 checks that prove this answer

You do not have to read these. They are part of the answer panel above, so pressing Run there executes all 7 of them and prints ok for each. That output is the proof, and the build fails if a single check fails.

7 checks

test('var ignores the block and is simply reassigned', shadow().loose, 'inner');
test('a let inside the block is a different variable', shadow().scoped, 'outer');
test('and so is a const', shadow().fixed, 'outer');
test('a var declared in a block outlives it', afterTheBlock().kept, 'still here');
test('a let does not', afterTheBlock().seen, 'ReferenceError');
test('reassigning a const throws', rebind, 'TypeError');
test('typeof a name that was never declared is safe', typeof neverDeclared, 'undefined');

The one to internalise is the second assertion. var has exactly one scope — the enclosing function — so writing var loose twice does not create two variables, it creates one and assigns to it twice. Every if, for and bare block you write with var is leaking into the function.

typeof neverDeclared returning 'undefined' instead of throwing is the one exception to "reading an undeclared name is an error". It is occasionally useful for feature detection, and it is also why a typo in a typeof check fails silently.

Newsletter

New writing, when it lands.

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