0
0
Javascriptprogramming~20 mins

Closures in Javascript - Practice Problems & Coding Challenges

Choose your learning style9 modes available
Challenge - 5 Problems
πŸŽ–οΈ
Closure Master
Get all challenges correct to earn this badge!
Test your skills under time pressure!
❓ Predict Output
intermediate
2: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]());
A0 0 0
B3 3 3
Cundefined undefined undefined
D0 1 2
Attempts:
2 left
πŸ’‘ Hint
Think about how the let keyword affects the loop variable scope inside closures.
❓ Predict Output
intermediate
2: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]());
A3 3 3
Bundefined undefined undefined
C0 0 0
D0 1 2
Attempts:
2 left
πŸ’‘ Hint
Consider how var differs from let in loops and closures.
🧠 Conceptual
advanced
1:30remaining
Why closures keep variables alive
Why do closures in JavaScript keep variables alive even after the outer function has finished?
ABecause closures create a copy of the variables and store them separately.
BBecause closures keep a reference to the variables in the outer function's scope, preventing garbage collection.
CBecause JavaScript automatically duplicates all variables used inside functions.
DBecause closures run the outer function again every time they are called.
Attempts:
2 left
πŸ’‘ Hint
Think about how memory and references work in JavaScript functions.
❓ Predict Output
advanced
1: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);
Aundefined
B123
C6
DNaN
Attempts:
2 left
πŸ’‘ Hint
Add the numbers passed through each function call.
❓ Predict Output
expert
2: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);
}
A3 3 3
B0 1 2
Cundefined undefined undefined
D0 0 0
Attempts:
2 left
πŸ’‘ Hint
Consider how var and asynchronous callbacks interact.