Recall & Review
beginner
What is a closure in JavaScript?
A closure is a function that remembers and can access variables from outside its own scope, even after the outer function has finished running.
Click to reveal answer
beginner
Why do closures remember variables from their outer function?
Because when a function is created inside another function, it keeps a reference to the outer function's variables, so it can use them later.
Click to reveal answer
intermediate
How can closures be useful in real life?
Closures help keep data private and create functions with their own memory, like counters or settings that remember past values.
Click to reveal answer
intermediate
What will the following code output and why?<br><pre>function makeCounter() {<br> let count = 0;<br> return function() {<br> count += 1;<br> return count;<br> }<br>}<br>const counter = makeCounter();<br>console.log(counter());<br>console.log(counter());</pre>It will output:<br>1<br>2<br>Because the inner function remembers the variable 'count' from makeCounter and increases it each time it is called.
Click to reveal answer
advanced
Can closures cause memory issues? Why or why not?
Yes, closures can keep variables in memory longer than needed if not managed carefully, because they hold references to outer variables even after the outer function ends.
Click to reveal answer
What does a closure allow a function to do?
✗ Incorrect
Closures let a function remember and access variables from the outer function's scope even after that function has returned.
In this code, what will be logged?<br>
function outer() {<br> let name = 'Alice';<br> return function() {<br> console.log(name);<br> }<br>}<br>const inner = outer();<br>inner();✗ Incorrect
The inner function remembers the variable 'name' from the outer function and logs 'Alice'.
Which of these is NOT a benefit of closures?
✗ Incorrect
Closures do not automatically free memory; in fact, they can keep variables in memory longer.
What happens if you create multiple closures from the same outer function?
✗ Incorrect
Each closure keeps its own copy of the outer function's variables, so they do not interfere with each other.
Which keyword is used to define a function that can create a closure?
✗ Incorrect
The 'function' keyword defines functions, which can create closures when nested.
Explain in your own words what a closure is and why it is useful.
Think about how a function can keep some information even after it finishes.
You got /3 concepts.
Describe a simple example where a closure helps keep track of a count or state.
Imagine a counter that remembers how many times it was called.
You got /3 concepts.