Intermediate Topic 34 of 54 Programming Fundamentals
Closures
Functions that capture variables from their defining scope.
How it works
A closure is a function bundled together with the variables of the scope in which it was defined, and those variables stay alive after the outer function returns. This lets the function keep private state without a class and allows function factories that produce customized behavior. The runtime keeps captured variables on the heap rather than the stack.
Step-by-step walkthrough
- make_counter() creates a local variable count.
- It defines an inner function that uses count.
- It returns the inner function, and count stays alive because it is captured.
- Each call to the inner function updates the same captured count.
- Each call to make_counter() gets its own separate count.
Where it is used
Counters, memoization wrappers, event handlers that remember context, callbacks that need configuration and module patterns for private data all use closures. They are fundamental to JavaScript and functional programming.
Common pitfall
Capturing loop variables by reference can make all callbacks see the last value in some languages. Closures can also keep large objects alive and cause memory leaks. Remember that captured variables are shared, not copied, so later changes are visible to every closure using them.
Where it fits in the course
Closures is topic 34 of 54 in Programming Fundamentals, rated Intermediate. It follows Lambda Expressions. The next topic is Iterators.
Practice and explore
- Open the interactive lesson, with a mini quiz.
- Take the Programming Fundamentals quiz.
How to study this topic
- Read the explanation above and restate the definition in your own words.
- Open the interactive lesson and answer its mini quiz.
- Read the common pitfall, then write a short example that avoids it.
- Check your understanding in the Programming Fundamentals quiz, and revisit the topic if you miss a question.
Frequently asked questions
What is Closures?
Where do people use Closures?
What is the most common mistake with Closures?
What should I learn before this topic?
How can I practice it?
Is Closures hard to learn?
How long does it take to learn Closures?
Which topics are related to Closures?
What should I study after Closures?
Related topics
- Lambda Expressions (Programming Fundamentals)
- Iterators (Programming Fundamentals)
- Higher-Order Functions (Programming Fundamentals)
- Generators (Programming Fundamentals)