
Closures in JavaScript: A Beginner-Friendly Guide
1. What is a Closure? In simple words: A Closure is when a function remembers the variables from its outer function even after the outer function has finished executing. Think of it like a school bag 🎒. A student goes home. But the bag still contains books from school . Even outside school, the books are still accessible. Similarly: A function can remember variables from where it was created . 2. Simple Example function outerFunction () { let message = " Hello Students " ; function innerFunction () { console . log ( message ); } return innerFunction ; } let myFunction = outerFunction (); myFunction (); Output Hello Students 3. How This Works Step by step: outerFunction() runs. It creates a variable message . innerFunction() is created inside it. outerFunction() returns innerFunction. Even after outerFunction() finishes, innerFunction() still remembers message . This memory is called a Closure . "That ability of remembering the outer variables is called a Closure." 4. Real-Life Example
Continue reading on Dev.to Tutorial
Opens in a new tab
