0
0
Javascriptprogramming~5 mins

Closures in Javascript - Cheat Sheet & Quick Revision

Choose your learning style9 modes available
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?
AChange the global variables directly
BRun faster than normal functions
CAccess variables from its outer function even after the outer function has finished
DCreate new variables in the global scope
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();
Anull
Bundefined
CError
D'Alice'
Which of these is NOT a benefit of closures?
AAutomatically freeing memory
BCreating private variables
CMaintaining state between function calls
DData privacy
What happens if you create multiple closures from the same outer function?
AAll closures share the same variables
BEach closure has its own separate copy of the outer variables
COnly the first closure works correctly
DClosures cannot be created multiple times
Which keyword is used to define a function that can create a closure?
Afunction
Bvar
Clet
Dconst
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.