Lesson 8 of 8

Functions that remember

Goal

Private data for a function without a global variable

01

Explanation

Every function in JavaScript keeps access to the variables that existed where it was created. If you return a function from inside another function, the inner one can still reach the outer one's variables even after the outer one has finished running. That's called a closure.

It's useful because it keeps data private without a global variable. The function makeCounter() creates let count = 0 and then returns a function that increments it. No other code can reach count except that function, and every call to makeCounter makes a new, independent counter. Many techniques you'll meet later rely on closures, such as throttling how often a function can run, memoization (saving a function's results so they aren't computed twice), and a function that only ever runs once.

The common mistake is to define the variable outside the function that makes the counter. Everything looks fine while you have only one counter, but as soon as you create a second one, you find that the two share the same count.

02

Your task

Write makeCounter() so it returns a function that gives 1 on the first call, then 2, then 3, and write once(fn) so it returns a function that calls fn the first time only, then returns that same first result on every call after that.

Checks

6 checks
  1. The counter remembers its value and gives 1, then 2, then 3
  2. Each counter keeps its own count
  3. The function passed to once is called only once
  4. The function from once returns the first result on every call
  5. Each function made by once keeps its own state
  6. The "Start the tour" button works only once
03

Hints

0/3
Track lessons0 of 8 done

Work with data, functions and operations that take time, and build up to an interface that creates its elements from data.

Intermediate level, 8 lessons, 2 hours in total.

index.html
Preview
index.html100%
–/6

Press “Run and check” to grade your code.

6 checks listed under “Your task”.

Track lessons0 of 8 done

Work with data, functions and operations that take time, and build up to an interface that creates its elements from data.

Intermediate level, 8 lessons, 2 hours in total.