JavaScript AcademyProfessional Engineering

Learning object 34 of 100

Closure visualizer

Step through creating counters and factories and watch each returned function keep its own variables alive after the outer function has returned.

Loading…

What it shows

When a function is created inside another, it keeps access to the outer variables. Each call of the outer function creates a separate set of those variables, so two counters from the same factory count independently. With var in a loop all callbacks share one variable; let gives each iteration its own.

Guided experiment

  1. In Two counters, step until likes has been called twice. What is views' count?
  2. In Factory, make a third discount and predict its result.
  3. In Loop trap, compare the var and let results.

Predict

function mk() { let n = 0; return () => ++n; } const f = mk(); f(); f(); What does the next f() return?

Related

Lessons: Lesson 48: Closures

Projects: Project 9: Shopping Cart Price Calculator

Source: web/assets/js/objects/object-034.js in the companion repository.