Bird
Raised Fist0
Javascriptprogramming~10 mins

Closures in Javascript - Step-by-Step Execution

Choose your learning style10 modes available
Concept Flow - Closures
Define outer function
↓
Create inner function
↓
Return inner function
↓
Call outer function -> returns inner
↓
Call inner function
↓
Inner accesses outer's variables
↓
Use preserved variables even after outer ends
Closure happens when an inner function remembers and uses variables from its outer function even after the outer function has finished running.
Execution Sample
Javascript
function outer() {
  let count = 0;
  return function inner() {
    count++;
    return count;
  };
}
const counter = outer();
counter();
This code creates a counter function that remembers how many times it was called by keeping 'count' inside a closure.
Execution Table
StepActionVariables StateOutput
1Call outer()count = 0Returns inner function
2Assign returned inner to countercount = 0 (inside closure)No output
3Call counter()count = 0 -> count = 1Returns 1
4Call counter() againcount = 1 -> count = 2Returns 2
5Call counter() third timecount = 2 -> count = 3Returns 3
💡 No more calls to counter(), closure preserves 'count' between calls
Variable Tracker
VariableStartAfter call 1After call 2After call 3
count0123
Key Moments - 3 Insights
Why does 'count' keep its value between calls to counter()?
Because the inner function forms a closure that keeps 'count' alive even after outer() finishes, as shown in execution_table rows 3-5.
Is 'count' accessible outside the outer() function directly?
No, 'count' is only accessible inside the inner function returned by outer(), so it is private and preserved in the closure.
What happens if we call outer() again and assign to a new variable?
A new closure with its own separate 'count' variable is created, independent from the first one.
Visual Quiz - 3 Questions
Test your understanding
Look at the execution_table, what is the value of 'count' after the second call to counter()?
A3
B1
C2
D0
💡 Hint
Check execution_table row 4 under Variables State showing count changes
At which step does the inner function get returned from outer()?
AStep 1
BStep 2
CStep 3
DStep 4
💡 Hint
Look at execution_table row 1 where outer() returns the inner function
If we call outer() again and assign to a new variable, what happens to 'count' in the new closure?
AIt shares the same 'count' as the first closure
BIt resets 'count' to 0 for the new closure
CIt causes an error
DIt deletes the old 'count'
💡 Hint
Refer to key_moments explanation about creating new closures with separate variables
Concept Snapshot
Closures in JavaScript:
- Inner functions remember variables from outer functions.
- Variables stay alive after outer finishes.
- Useful for private data and counters.
- Syntax: function outer() { let x; return function inner() { use x } }
- Calling outer() returns inner with preserved variables.
Full Transcript
Closures happen when a function inside another function remembers the outer function's variables even after the outer function ends. In the example, outer() defines a variable 'count' and returns an inner function that increases and returns 'count'. When we call outer(), it returns this inner function, which keeps 'count' alive. Each time we call the returned function, 'count' increases by one. This shows how closures keep data private and persistent between calls. If we call outer() again, a new closure with a new 'count' starts fresh. This is useful for making counters or private variables in JavaScript.

Practice

(1/5)
1. What is a closure in JavaScript?
easy
A. A function that has no parameters
B. A function that runs only once
C. A function that returns another function without variables
D. A function that remembers variables from its creation context

Solution

  1. Step 1: Understand closure definition

    A closure is a function that keeps access to variables from the place where it was created, even after that place has finished running.
  2. Step 2: Match definition to options

    A function that remembers variables from its creation context correctly describes this behavior, while others describe unrelated concepts.
  3. Final Answer:

    A function that remembers variables from its creation context -> Option D
  4. Quick Check:

    Closure = function remembering variables [OK]
Hint: Closures remember variables from where they were made [OK]
Common Mistakes:
  • Thinking closures are functions without parameters
  • Confusing closures with immediately invoked functions
  • Believing closures only run once
2. Which of the following is the correct syntax to create a closure in JavaScript?
easy
A. function outer() { let x = 5; function inner() { return x; } }
B. function outer() { let x = 5; return x; }
C. function outer() { let x = 5; return function inner() { return x; } }
D. function outer() { return function() { let x = 5; } }

Solution

  1. Step 1: Identify closure syntax

    A closure requires an inner function that accesses variables from the outer function and is returned so it can be used later.
  2. Step 2: Check options for correct closure

    function outer() { let x = 5; return function inner() { return x; } } returns an inner function that uses outer variable x, forming a closure. Others either don't return the function or don't access outer variables correctly.
  3. Final Answer:

    function outer() { let x = 5; return function inner() { return x; } } -> Option C
  4. Quick Check:

    Return inner function accessing outer variable [OK]
Hint: Closure needs returned inner function accessing outer variable [OK]
Common Mistakes:
  • Not returning the inner function
  • Returning only the variable, not a function
  • Defining inner function but not using outer variables
3. What will be the output of the following code?
function makeCounter() {
  let count = 0;
  return function() {
    count += 1;
    return count;
  };
}
const counter = makeCounter();
console.log(counter());
console.log(counter());
medium
A. 1 and 2
B. 0 and 1
C. undefined and undefined
D. 1 and 1

Solution

  1. Step 1: Understand closure behavior in makeCounter

    The inner function increments count and returns it. The variable count is remembered by the closure.
  2. Step 2: Trace the calls to counter()

    First call: count = 0 + 1 = 1, returns 1. Second call: count = 1 + 1 = 2, returns 2.
  3. Final Answer:

    1 and 2 -> Option A
  4. Quick Check:

    Closure keeps count incrementing: 1, 2 [OK]
Hint: Closure keeps variable state between calls [OK]
Common Mistakes:
  • Thinking count resets each call
  • Expecting output 1 and 1
  • Confusing closure with global variable
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]());
console.log(functions[1]());
medium
A. All functions return 3 instead of 0, 1, 2
B. Syntax error due to missing semicolons
C. Functions return undefined
D. Functions throw a ReferenceError

Solution

  1. Step 1: Identify loop variable scope

    The loop uses var i, which is function-scoped, so all inner functions share the same i.
  2. Step 2: Understand closure captures final i value

    After loop ends, i is 3. All functions return 3, not 0, 1, 2 as expected.
  3. Final Answer:

    All functions return 3 instead of 0, 1, 2 -> 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 ReferenceError or undefined
5. How can you fix the following code so each function remembers its own value of i?
function createFuncs() {
  let funcs = [];
  for (var i = 0; i < 3; i++) {
    funcs.push(function() { return i; });
  }
  return funcs;
}
hard
A. Use var but call the function immediately
B. Change var to let in the for loop declaration
C. Return i directly instead of a function
D. Declare i as a global variable

Solution

  1. Step 1: Understand block scope with let

    Using let in the for loop creates a new binding of i for each iteration, so closures capture different i values.
  2. Step 2: Compare with var behavior

    var is function-scoped, so all closures share the same i. Changing to let fixes this by giving each iteration its own i.
  3. Final Answer:

    Change var to let in the for loop declaration -> Option B
  4. Quick Check:

    let in loop creates separate i per iteration [OK]
Hint: Use let in loops to create separate closure variables [OK]
Common Mistakes:
  • Trying to fix by making i global
  • Returning i instead of function
  • Using var with immediate call but misunderstanding closures
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