liveBook · Manning

Let keyword

As explained in Secrets of the JavaScript Ninja, Third Edition

let is a JavaScript keyword that declares a block-scoped, reassignable binding.

The JavaScript keyword `let` declares a block-scoped binding that can be reassigned. Its scope is the nearest enclosing block, such as a function body, an `if` statement, or a standalone pair of curly braces. section 7.3.1 section 7.6

Keep these rules in mind:

  • A `for` loop’s initializer belongs to the loop’s scope, and each iteration creates a new scope. section 7.3.1
  • A `let` binding cannot be accessed before its declaration executes; doing so throws a `ReferenceError` while the binding is in the temporal dead zone. section 7.3.2
Listing 7.5 Loop scope and closures
for (let i = 0; i < 3; i++) {
  setTimeout(() => {
    console.log(i);
  }, 10);
}

In this timer example, each callback logs the value of `i` from the iteration that created it, rather than all callbacks sharing one final loop value. section 7.3.1

How Secrets of the JavaScript Ninja, Third Edition covers it

How deep it goes
Explains block scope, per-iteration loop scope, and the temporal dead zone without detailing engine internals.
Examples
Uses nested blocks and a timer loop to demonstrate scope and closure behavior.
What you can do after
Apply `let` to declare block-scoped bindings and predict loop-closure values and pre-initialization errors.
How it connects
Connects `let` to block scope, closures, `const`, `var`, and the temporal dead zone.

Also explained in

Compare how 5 books explain let keyword →

Related concepts

This explainer was generated by Manning's knowledge graph from the text of Secrets of the JavaScript Ninja, Third Edition. The section links point to the parts of the book it draws on.