liveBook · Manning

Let keyword

As explained in JavaScript in Depth

A JavaScript block-scoped variable-declaration keyword whose binding must be initialized before it can be accessed.

Calling a function before its surrounding name declaration can behave differently depending on the declaration keyword. With var, the name exists as undefined; with let, accessing it before assignment throws an error. section 6.2.1

let makes execution order visible at the point of use: the binding cannot be successfully read until its declaration has initialized it. This avoids silently passing undefined into code that runs too early. section 6.2.1

Early access fails

greet(); let name = 'Sally'; function greet() { console.log(`Hello, ${name}`); } The call reaches name before its let declaration has initialized the binding, so execution throws instead of logging a greeting with undefined. section 6.2.1

How JavaScript in Depth covers it

How deep it goes
Explains the runtime difference from var through a small example, but does not detail the formal initialization model.
Examples
Uses an early greet call that references name before a later let declaration, contrasted with var-based behavior.
What it assumes
Assumes familiarity with JavaScript functions and variable declarations while contrasting modern let and const with var.
What you can do after
Diagnose early-access failures by checking whether a let binding has been initialized before the executing code reads it.
How it connects
Contrasts let with var and const, and connects it to hoisting, function declarations, and function expressions.

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 JavaScript in Depth. The section links point to the parts of the book it draws on.