Challenge - 5 Problems
Closure Mastery
Get all challenges correct to earn this badge!
Test your skills under time pressure!
β Predict Output
intermediate2:00remaining
Closure and private variables
What is the output of this code when calling
counter.increment() three times and then counter.get()?Javascript
function createCounter() { let count = 0; return { increment() { count++; }, get() { return count; } }; } const counter = createCounter(); counter.increment(); counter.increment(); counter.increment(); console.log(counter.get());
Attempts:
2 left
π‘ Hint
Think about how the variable
count is kept inside the function and accessed only through returned methods.β Incorrect
The variable
count is private inside createCounter. Each call to increment() increases it by 1. After three increments, get() returns 3.β Predict Output
intermediate2:00remaining
Closure capturing loop variable
What will be logged by the following 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
Remember that
var is function-scoped, not block-scoped.β Incorrect
The variable
i is shared in the loop because it is declared with var. When the functions run, i is 3, so all return 3.β Predict Output
advanced2:00remaining
Fixing closure in loop with IIFE
What is the output of this fixed code?
Javascript
function createFunctions() { const funcs = []; for (var i = 0; i < 3; i++) { (function(j) { funcs.push(function() { return j; }); })(i); } return funcs; } const functions = createFunctions(); console.log(functions[0]()); console.log(functions[1]()); console.log(functions[2]());
Attempts:
2 left
π‘ Hint
The IIFE captures the current value of
i as j for each function.β Incorrect
The IIFE creates a new scope for each iteration, capturing the current
i value as j. Each function returns its own j value.π§ Conceptual
advanced1:30remaining
Why use closures for data privacy?
Which of the following best explains why closures are used to create private data in JavaScript?
Attempts:
2 left
π‘ Hint
Think about how inner functions remember variables from where they were created.
β Incorrect
Closures keep the variables alive in the outer function's scope, allowing inner functions to access them even after the outer function returns, enabling data privacy.
β Predict Output
expert2:00remaining
Closure with asynchronous callbacks
What will be the output of this code snippet?
Javascript
function delayedLogger() { for (let i = 0; i < 3; i++) { setTimeout(() => { console.log(i); }, 100); } } delayedLogger();
Attempts:
2 left
π‘ Hint
Consider how
let differs from var in loops and closures.β Incorrect
Using
let creates a new binding for each loop iteration, so each callback logs its own i value.