Scope and Closures

Where can a variable be seen, and why can a function still use a variable after the code that made it has finished? Learn scope, why modern code uses let and const instead of var, and closures: functions that remember.

Updated

Scope in JavaScript

  1. Scope: Where a Variable Can Be Seen (Apprentice): Scope is the part of a program where a variable can be seen and used, and knowing its three kinds (global, function and block) explains a whole family of "is not defined" errors and values that won't change.
  2. Hoisting, var and the Temporal Dead Zone (Journeyman): Before JavaScript runs a scope it notes every declaration in it, which is why a function can be called above the line that makes it, why var gives undefined there, and why let and const stop with an error instead.

Closures in JavaScript

  1. Closures: Functions That Remember (Journeyman): A closure is a function together with the variables it could see where it was made, so it keeps using them after the function that made them has finished.
  2. Closures at Work: Private State and Factories (Journeyman): Put closures to work to keep a count that no other code can change, to build as many independent counters as you need with a factory function, and to make a function that runs only once.

Exercise: Arcade Token Counters

  1. Exercise: Arcade Token Counters (Journeyman): Write the Starlight Arcade's token counters, prize-ticket machine and once-only welcome bonus, each keeping its count private in a closure, and let the tests check each one.