MEPX
Chapter 3 of 16All chapters

Chapter 3 of 16

Variables and scope

let, const, var and where each one lives.

Three keywords, two behaviours

let and const only exist inside the block they are declared in. var ignores blocks and belongs to the whole function, which is why it surprises people inside loops and if statements.

  • Default to const, use let when the value must change, and avoid var in new code.
  • const stops you reassigning the binding, not changing what it points at.

Hoisting

Declarations are processed before the code runs. A var is created early and holds undefined, while let and const exist but cannot be touched until the line that declares them, which throws a ReferenceError.