Closures & Scope

Loop Closures

Loop Closures

Closures capture variables, not snapshots of values. With `var), a loop has one shared binding for the whole loop, so every saved function reads the same variable later.

This is one reason modern JavaScript usually uses let for loop counters. A block-scoped loop counter gives each iteration its own binding.

Your task: Read the commented code in the starter. Predict the array returned by the final line, and assign that array to prediction.

Free with a JS Exercises account

Sign in to start coding, run your solution, and keep your progress saved for later. No payment needed.

By continuing, you agree to our Terms and Privacy Policy. We'll send occasional product updates and news. You can unsubscribe anytime.

Loop Closures

Closures capture variables, not snapshots of values. With `var), a loop has one shared binding for the whole loop, so every saved function reads the same variable later.

This is one reason modern JavaScript usually uses let for loop counters. A block-scoped loop counter gives each iteration its own binding.

Your task: Read the commented code in the starter. Predict the array returned by the final line, and assign that array to prediction.

Free with a JS Exercises account

Sign in to start coding, run your solution, and keep your progress saved for later. No payment needed.

By continuing, you agree to our Terms and Privacy Policy. We'll send occasional product updates and news. You can unsubscribe anytime.

Console

Run code to see output.