typestar

let, const and the dead zone in JavaScript

Block scoping, and why a let is unusable before its declaration.

function scoping() {
  const results = [];

  if (true) {
    var leaks = "function scoped";
    let contained = "block scoped";
    results.push(contained);
  }
  results.push(leaks);

  try {
    early;
    let early = 1;
  } catch (error) {
    results.push(error.constructor.name);
  }

  const config = { theme: "dark" };
  config.theme = "light"; // allowed: the binding is const, not the object
  results.push(config.theme);
  return results;
}

console.log(scoping());

How it works

  1. let and const are block-scoped; var is function-scoped.
  2. Touching a let before its line throws a ReferenceError.
  3. const freezes the binding, not the object it points at.

Keywords and builtins used here

The run, in numbers

Lines
24
Characters to type
430
Tokens
106
Three-star pace
80 tpm

At the three-star pace of 80 tokens a minute, this run takes about 80 seconds.

Type this snippet

Step 2 of 5 in Bindings & values, step 2 of 43 in Language basics.

← Previous Next →