Bird
Raised Fist0
Javascriptprogramming~20 mins

Practical closure use cases in Javascript - Practice Problems & Coding Challenges

Choose your learning style10 modes available
Challenge - 5 Problems
πŸŽ–οΈ
Closure Mastery
Get all challenges correct to earn this badge!
Test your skills under time pressure!
❓ Predict Output
intermediate
2: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());
A0
BTypeError
Cundefined
D3
Attempts:
2 left
πŸ’‘ Hint
Think about how the variable count is kept inside the function and accessed only through returned methods.
❓ Predict Output
intermediate
2: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]());
A3 3 3
B0 1 2
Cundefined undefined undefined
D0 0 0
Attempts:
2 left
πŸ’‘ Hint
Remember that var is function-scoped, not block-scoped.
❓ Predict Output
advanced
2: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]());
Aundefined undefined undefined
B3 3 3
C0 1 2
DTypeError
Attempts:
2 left
πŸ’‘ Hint
The IIFE captures the current value of i as j for each function.
🧠 Conceptual
advanced
1:30remaining
Why use closures for data privacy?
Which of the following best explains why closures are used to create private data in JavaScript?
AClosures allow functions to access variables from their outer scope even after the outer function has finished executing.
BClosures prevent any function from accessing variables outside its own scope.
CClosures automatically encrypt variables to keep them private.
DClosures make variables global so all functions can share them.
Attempts:
2 left
πŸ’‘ Hint
Think about how inner functions remember variables from where they were created.
❓ Predict Output
expert
2: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();
Aundefined undefined undefined
B0 1 2
C3 3 3
D0 0 0
Attempts:
2 left
πŸ’‘ Hint
Consider how let differs from var in loops and closures.

Practice

(1/5)
1. What is the main benefit of using closures in JavaScript?
easy
A. They make code run faster by optimizing loops.
B. They allow functions to remember variables from their creation context.
C. They automatically free memory when variables are no longer used.
D. They let you write code without using functions.

Solution

  1. Step 1: Understand closure concept

    Closures let a function remember variables from the place where it was created, even after that place has finished running.
  2. Step 2: Compare options

    Only They allow functions to remember variables from their creation context. correctly describes this key feature. Other options describe unrelated or incorrect ideas.
  3. Final Answer:

    They allow functions to remember variables from their creation context. -> Option B
  4. Quick Check:

    Closure = Remember variables [OK]
Hint: Closures remember variables where functions are made [OK]
Common Mistakes:
  • Thinking closures speed up code automatically
  • Confusing closures with garbage collection
  • Believing closures remove the need for functions
2. Which of the following is the correct syntax to create a closure that keeps a private counter?
easy
A. function counter() { return count++; let count = 0; }
B. function counter() { var count = 0; count++; return count; }
C. let count = 0; function counter() { count++; return count; }
D. function counter() { let count = 0; return function() { count++; return count; }; }

Solution

  1. Step 1: Identify closure pattern

    function counter() { let count = 0; return function() { count++; return count; }; } defines a function that returns another function which accesses the variable 'count' inside its scope, creating a closure.
  2. Step 2: Check other options

    function counter() { var count = 0; count++; return count; } increments count but does not return a function, so no closure. let count = 0; function counter() { count++; return count; } uses a global variable, not private. function counter() { return count++; let count = 0; } has syntax error (return before variable declaration).
  3. Final Answer:

    function counter() { let count = 0; return function() { count++; return count; }; } -> Option D
  4. Quick Check:

    Closure = function inside function with private variable [OK]
Hint: Closure needs inner function accessing outer variable [OK]
Common Mistakes:
  • Returning value instead of function for closure
  • Using global variables instead of private ones
  • Placing return before variable declaration
3. What will be the output of the following code?
function makeAdder(x) {
  return function(y) {
    return x + y;
  };
}
const add5 = makeAdder(5);
console.log(add5(3));
medium
A. 53
B. NaN
C. 8
D. undefined

Solution

  1. Step 1: Understand makeAdder function

    makeAdder returns a function that adds its argument y to x, which is remembered via closure.
  2. Step 2: Calculate add5(3)

    add5 is makeAdder(5), so x=5. Calling add5(3) returns 5 + 3 = 8.
  3. Final Answer:

    8 -> Option C
  4. Quick Check:

    Closure adds remembered x to y = 8 [OK]
Hint: Closure remembers x=5, adds y=3 to get 8 [OK]
Common Mistakes:
  • Concatenating numbers as strings
  • Forgetting closure remembers x
  • Expecting undefined or NaN
4. Find the error in this closure example:
function createFuncs() {
  let funcs = [];
  for (var i = 0; i < 3; i++) {
    funcs.push(function() { return i; });
  }
  return funcs;
}
const functions = createFuncs();
console.log(functions[0]());
medium
A. All functions return 3 instead of 0, 1, 2 due to var scoping.
B. Syntax error because of missing semicolons.
C. functions array is empty because push is not called.
D. The code runs correctly and prints 0.

Solution

  1. Step 1: Analyze loop variable scope

    Using var for i means one shared variable. All functions capture the same i, which after loop ends is 3.
  2. Step 2: Understand closure effect

    Each function returns i, but i is 3 at call time, so all return 3, not 0,1,2.
  3. Final Answer:

    All functions return 3 instead of 0, 1, 2 due to var scoping. -> Option A
  4. Quick Check:

    var in loop causes shared i = 3 [OK]
Hint: var in loop shares variable; use let for block scope [OK]
Common Mistakes:
  • Assuming each function captures separate i
  • Thinking semicolons cause error
  • Expecting functions array to be empty
5. How can you modify this code to create an array of functions each returning its own index?
function createFuncs() {
  let funcs = [];
  for (var i = 0; i < 3; i++) {
    funcs.push(function() { return i; });
  }
  return funcs;
}
const functions = createFuncs();
console.log(functions[0](), functions[1](), functions[2]());
hard
A. Replace var with let in the for loop declaration.
B. Declare i with var but add a closure with an IIFE inside the loop.
C. Use a global variable instead of i.
D. No change needed; code works as is.

Solution

  1. Step 1: Understand problem with var

    var is function-scoped, so all functions share same i, which ends at 3.
  2. Step 2: Fix with let for block scope

    Replacing var with let makes i block-scoped, so each iteration has its own i captured by closure.
  3. Final Answer:

    Replace var with let in the for loop declaration. -> Option A
  4. Quick Check:

    let creates separate i per loop iteration [OK]
Hint: Use let in loops to create separate closure variables [OK]
Common Mistakes:
  • Using global variables causing shared state
  • Thinking IIFE is only solution
  • Believing code works without changes
Recommended

Ready to prove it?

Pass the test and this pattern moves unknown strong while earning +1 Grip toward your certificate.

10 questions~5 mineasy hard