Closures — Complete Guide
Closures — Complete Guide: free step-by-step lesson with examples, common mistakes, and interview tips — part of JavaScript Tutorial on Toolliyo Academy.
On this page
JavaScript Tutorial · Lesson 16 of 100
Closures
Basics → Objects & data → Async & DOM → Advanced → Tools → Projects
Beginner · 1 — Learn by example · ~6 min · JS Control Flow & Functions
What is this?
A closure is when an inner function remembers variables from the outer function, even after the outer function has finished running.
Why should you care?
Closures power counters, private data, and callbacks — they appear in almost every real JavaScript app.
See it live — copy this example
Paste into an HTML file or the browser console (F12). Use Run below when the live editor is available.
function makeCounter() {
let count = 0;
return function () {
count++;
return count;
};
}
const counter = makeCounter();
console.log(counter());
console.log(counter());
Run Example »
Edit the code below and click Run to see the result in Toolliyo’s live editor.
What happened?
- makeCounter returns an inner function.
- That inner function closes over count, so count stays alive between calls.
Practice next
- Run counter() five times and watch count grow.
- Create two counters with makeCounter() and show separate counts.
- Trace count on paper through each call.
- Add a reset() method using a closure that sets count back to 0.
- Build makeMultiplier(factor) that returns a function multiplying by factor.
Remember
Inner functions remember outer variables Used for private state Very common in callbacks
ScriptVerse rate limiter
A private attempt counter inside a login form closure tracks failed tries without exposing count on window.
Outcome: Closures hide internal state while exposing only safe public functions.
Interview prep for this lesson
Practice these questions aloud after reading—each links to a full structured answer.
Sign in to ask a question or upvote helpful answers.
No questions yet — be the first to ask!