Challenge - 5 Problems
Closure Master
Get all challenges correct to earn this badge!
Test your skills under time pressure!
β Predict Output
intermediate2:00remaining
Output of a closure with loop variable
What is the output of the following code snippet?
Javascript
function createFunctions() { const funcs = []; for (let i = 0; i < 3; i++) { funcs.push(function() { return i; }); } return funcs; } const functions = createFunctions(); console.log(functions[0]()); console.log(functions[1]()); console.log(functions[2]());
Attempts:
2 left
π‘ Hint
Think about how the
let keyword affects the loop variable scope inside closures.β Incorrect
Using
let in the loop creates a new binding for each iteration, so each function remembers its own i value.β Predict Output
intermediate2:00remaining
Closure capturing variable after loop with var
What will be printed by this code?
Javascript
function createFunctions() { const funcs = []; for (var i = 0; i < 3; i++) { funcs.push(function() { return i; }); } return funcs; } const functions = createFunctions(); console.log(functions[0]()); console.log(functions[1]()); console.log(functions[2]());
Attempts:
2 left
π‘ Hint
Consider how
var differs from let in loops and closures.β Incorrect
Using
var declares i in function scope, so all functions share the same i which ends at 3 after the loop.π§ Conceptual
advanced1:30remaining
Why closures keep variables alive
Why do closures in JavaScript keep variables alive even after the outer function has finished?
Attempts:
2 left
π‘ Hint
Think about how memory and references work in JavaScript functions.
β Incorrect
Closures keep references to variables in their outer scope, so those variables stay in memory as long as the closure exists.
β Predict Output
advanced1:30remaining
Output of nested closures with parameters
What is the output of this code?
Javascript
function outer(x) { return function inner(y) { return function innermost(z) { return x + y + z; }; }; } const result = outer(1)(2)(3); console.log(result);
Attempts:
2 left
π‘ Hint
Add the numbers passed through each function call.
β Incorrect
Each function returns another function that remembers the parameters passed, so the final sum is 1 + 2 + 3 = 6.
β Predict Output
expert2:00remaining
Closure with asynchronous behavior and loop
What will this code print to the console?
Javascript
for (var i = 0; i < 3; i++) { setTimeout(function() { console.log(i); }, 100); }
Attempts:
2 left
π‘ Hint
Consider how
var and asynchronous callbacks interact.β Incorrect
The loop finishes before the timeouts run, so
i is 3 in all callbacks, printing 3 three times.