- Executors
-
Learn
Learn Python Runnable examples, NumPy, pandas, and more Learn AI / Machine LearningNeural networks, ML and LLMs from scratch Learn C & C++ Pointers, memory, STL, and modern C++ Learn C#C# basics, OOP, LINQ, async, and .NET exercises Learn MatplotlibLine, bar, scatter and pie charts with live visualizers Learn RustOwnership, traits, error handling, and threads Learn GoSlices, interfaces, goroutines, and channels Python Algorithms Search, sorting, recursion, and visualizers O(n) C & C++ Algorithms Compare algorithms implemented in C and C++ Coding for Kids Learn to code by playing!
- QuizzesNew
- ChallengesNew
- For TeachersNew
- Updates
- Buy me a coffee
JavaScript Closures in Loops Quiz
This JavaScript quiz is all about the "closures in a loop" interview question. You will predict what functions created inside for and while loops remember, see why var and let behave differently, and pick the right fix.
Sample question
Question 1 of 10What does this print?
const fns = [];
for (var i = 0; i < 3; i++) {
fns.push(() => i);
}
console.log(fns.map((f) => f()).join(","));
Show the answer
C. 3,3,3 var is function scoped, so there is one i shared by all three closures. They run after the loop has finished, when i is 3 (the value that ended the loop).
What this quiz covers
- Why
varin a loop gives every closure the same variable - The per-iteration binding of
letinforloops - Fixing the loop with an IIFE or a callback parameter
- Variables declared outside the loop
constin a classicforloop
Questions people ask
Do I need an account?
No. Anyone can play. Sign in to keep your XP, streak, badges and history.
Can I retake it?
Yes. Your best score is kept, and the questions and answers are shuffled each time.