Closures
A closure is a function that remembers its outer variables even after the outer function has finished running.
Learning Goals
The Core Concept
Closures are a confusing but powerful concept. In JavaScript, a closure gives you access to an outer function's scope from an inner function.
Closures are created every time a function is created. They are commonly used for data privacy, creating 'private' variables that cannot be modified directly from the outside.
Visual guide
JavaScript concept flow
A simple original diagram to connect the lesson idea with real project flow.
Code & Implementation
function createCounter() {
let count = 0; // 'count' is a private variable
return function() {
count = count + 1; // It remembers 'count' from the outer scope
return count;
};
}
const myCounter = createCounter();
console.log(myCounter()); // 1
console.log(myCounter()); // 2
console.log(myCounter()); // 3
// There is no way to directly change 'count' from the outside!Expected Output
1 2 3
Practical Project: Closures Implementation
Hands-on practice task
The Challenge
Apply your knowledge of Closures to build a real-world feature. This project helps you move beyond theory and understand how JavaScript works in professional settings.
Helpful Hints
- •Refer back to the 'Steps' section for the correct sequence.
- •Check the 'Tips' for common optimization patterns.
- •Look at the 'Code Highlights' to ensure you're using the right syntax.
Quick Knowledge Check
Why would I use a closure instead of a global variable?
Continue Learning
Next steps after this lesson
Apply your knowledge of Closures to build a real-world feature. This project helps you move beyond theory and understand how JavaScript works in professional settings.
Ready to put your coding skills to the test?
Don't just read—write code! Use our free Try-Code Playground to experiment with real-time preview, or search utilities on our Developer Tools List.