Hey friends! π
I couldn't make it yesterday and I feel sad about that π. I lost a relative so I was at her wake. But I'm here today :)
Today is closures, one of those concepts that seems a bit complex but actually very practical once you see it in action.
Closures occur when a function remembers variables from its outer scope, even after that outer function has finished running.
Example 1: Basic Closure
function greet(name) {
const greeting = 'Hello';
return function() {
console.log(`${greeting}, ${name}!`);
}
}
const sayHello = greet('Alice');
sayHello(); // "Hello, Alice!"
Hereβs whatβs happening:
-
greet('Alice')returns a function. - That returned function remembers the variables
greetingandname. - Even though
greethas finished executing,sayHello()still works.
Example 2: Counter with Closure
Closures are perfect for keeping private variables.
function createCounter() {
let count = 0;
return function() {
count++;
return count;
}
}
const counter = createCounter();
console.log(counter()); // 1
console.log(counter()); // 2
console.log(counter()); // 3
-
countis private. You canβt access it directly from outside. - Each call remembers the previous value.
Example 3: Real-World Use Case
function makeMultiplier(x) {
return function(y) {
return x * y;
}
}
const double = makeMultiplier(2);
const triple = makeMultiplier(3);
console.log(double(5)); // 10
console.log(triple(5)); // 15
Closures let us create flexible and reusable functions.
Here is a Challenge for You
No codepen today but can you answer the question below?
function secretPassword(password) {
return function(guess) {
return guess === password ? 'Access granted' : 'Access denied';
}
}
const checkPassword = secretPassword('1234');
console.log(checkPassword('0000')); // ?
console.log(checkPassword('1234')); // ?
βWhy does this work even though secretPassword has finished running?β
ππΎββοΈ Wrap-Up
- A closure is a function remembering its scope even after execution.
- Useful for private data, partial application, and factory functions.
- Always think: βWhich variables does this function remember?β
Thatβs it for today!
What should we talk about next Wednesday? Drop it below π
Connect with me on GitHub
Was this tutorial helpful? Got questions? Drop them in the π¬, I love feedback.
Iβm keeping these light, fun, and useful, one small project at a time.
If you enjoyed this, leave a π¬ or π§‘ to let me know.
Follow me for more short, beginner-friendly JavaScript lessons every week.
I'm still hunting for full stack roles,
contract or full-time.
Please check out my [Portfolio](https://gift-egbonyi.onrender.com)
Web trails:
LinkedIn | X (Twitter)
See you next Wednesday π, on time!
Till then, write clean code and stay curious. π¦
Top comments (0)