JavaScript-Quiz: Closures in Loops

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.

Schwer 10 Fragen ~8 Minuten Bestanden ab 80% Node.js 22

Modus wählen

Du spielst als Gast: Melde dich an, damit XP und Serie gespeichert werden.

Beispielfrage

Frage 1 von 10

What does this print?

const fns = [];
for (var i = 0; i < 3; i++) {
  fns.push(() => i);
}
console.log(fns.map((f) => f()).join(","));
Lösung zeigen

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).

Darum geht es in diesem Quiz

  • Why var in a loop gives every closure the same variable
  • The per-iteration binding of let in for loops
  • Fixing the loop with an IIFE or a callback parameter
  • Variables declared outside the loop
  • const in a classic for loop

Häufige Fragen

Brauche ich ein Konto?

Nein. Jeder kann spielen. Mit Anmeldung werden XP, Serie, Abzeichen und Verlauf gespeichert.

Kann ich es wiederholen?

Ja. Dein Bestwert bleibt erhalten, und Fragen und Antworten werden jedes Mal neu gemischt.