Closures — Functions That Remember — Concept Check
Questions on Closures — Functions That Remember. A closure is a function together with the scope it was created in. It keeps that scope alive after the outer function has returned, which is how JavaScript does private state, factories, and almost every callback pattern.
Questions in this quiz
7 questions on Closures — Functions That Remember — Concept Check. Work through them here, then start the quiz to answer them and see your score.
1.A JavaScript function is returning another function that increments a counter. Why does each call to the outer function create an independent counter?
- AThe closure copies the outer function's variables.
- BThe counter is stored globally.
- CEach call creates a new scope with its own variables.
- DJavaScript resets the counter automatically.
2.Given the code snippet: `for (var i = 0; i < 3; i++) fns.push(() => i);`, what will `fns.map(f => f())` output?
- A[0, 1, 2]
- B[1, 2, 3]
- C[3, 3, 3]
- D[undefined, undefined, undefined]
3.In a React component using `useEffect`, why might a closure cause a 'stale closure' problem?
- AThe closure captures the initial state and doesn't update.
- BClosures always create memory leaks.
- CThe closure updates automatically with state changes.
- DClosures prevent component re-renders.
4.Why does using `let` in a loop, instead of `var`, result in different closure behavior?
- A`let` variables are immutable.
- B`let` is faster than `var`.
- C`let` variables are stored globally.
- D`let` creates a new binding for each iteration.
5.A developer uses a closure to debounce a search function. What is stored in the closure?
- AThe timer ID for managing the debounce.
- BThe search query results.
- CThe user's input history.
- DThe network request object.
6.Why might a closure be used in a memoization function?
- ATo store the cache that remembers previous computations.
- BTo prevent any changes to the function's input.
- CTo automatically parallelize function calls.
- DTo ensure functions run only once.
7.What happens when a closure captures a variable rather than its value?
- AThe closure creates a new variable copy.
- BThe closure sees the value at the time of creation.
- CThe closure sees the current value when the function runs.
- DThe closure prevents the variable from changing.