Bird
Raised Fist0
Javascriptprogramming~10 mins

Practical closure use cases in Javascript - Step-by-Step Execution

Choose your learning style10 modes available
Concept Flow - Practical closure use cases
Define outer function
↓
Create inner function
↓
Return inner function
↓
Call outer function -> get inner function
↓
Call inner function -> access outer variables
↓
Use closure for data privacy or state retention
Closure happens when an inner function remembers variables from its outer function even after the outer function has finished running.
Execution Sample
Javascript
function counter() {
  let count = 0;
  return function() {
    count++;
    return count;
  };
}
const c = counter();
c();
c();
This code creates a counter that remembers its count value between calls using closure.
Execution Table
StepActioncount ValueReturned ValueExplanation
1Call counter()0function (inner function)Outer function runs, count initialized to 0, inner function returned
2Call c() first time11Inner function increments count to 1 and returns it
3Call c() second time22Inner function increments count to 2 and returns it
4No more calls2-Execution stops, count retains value 2 inside closure
💡 No more calls to inner function, closure retains count value 2
Variable Tracker
VariableStartAfter 1After 2Final
countundefined0 (in counter)1 (after first c())2 (after second c())
Key Moments - 3 Insights
Why does the inner function remember the variable 'count' even after counter() finished?
Because the inner function forms a closure that keeps access to 'count' from the outer function's scope, as shown in execution_table steps 2 and 3.
What happens if we call counter() again and assign it to a new variable?
A new closure is created with its own separate 'count' variable starting at 0, independent from the first closure.
Can the variable 'count' be accessed directly from outside the closure?
No, 'count' is private inside the closure and can only be accessed or changed by calling the inner function.
Visual Quiz - 3 Questions
Test your understanding
Look at the execution table, what is the value of 'count' after the second call to c()?
A2
B1
C0
Dundefined
💡 Hint
Check the 'count Value' column at step 3 in the execution_table.
At which step does the inner function first increment 'count'?
AStep 1
BStep 2
CStep 3
DStep 4
💡 Hint
Look at the 'Action' and 'count Value' columns in execution_table for when count changes from 0 to 1.
If we create a new counter by calling counter() again, what will be the initial 'count' value inside that new closure?
A2
B1
C0
Dundefined
💡 Hint
Refer to key_moments about new closures having their own separate 'count' starting at 0.
Concept Snapshot
Closure lets an inner function remember variables from its outer function.
Syntax: outer returns inner function that uses outer variables.
Use closures to keep data private or remember state.
Each closure has its own copy of variables.
Call outer function to get inner function with closure.
Call inner function to access or update closed-over variables.
Full Transcript
This visual execution shows how closures work in JavaScript using a counter example. The outer function 'counter' defines a variable 'count' and returns an inner function that increments and returns 'count'. When we call 'counter()', it returns the inner function which remembers 'count' even after 'counter' finishes. Each call to the inner function increases 'count' by 1 and returns it. The variable 'count' is private and cannot be accessed directly from outside. This example demonstrates practical use of closures for data privacy and state retention.

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