
JavaScript Closures Explained Simply with Examples
What is a Closure: A closure is a function that remembers the variables from its outer function even after the outer function has finished executing. example: function outer () { let name = " Bala " ; function inner () { console . log ( name ); } return inner ; } const myFunction = outer (); myFunction (); Output: Bala step by step Explanation: 1.outer() function runs 2.Variable name is created 3.inner() function is returned 4.Even after outer() finishes, inner() still remembers name 5.This is called closure **Why Do We Use Closures in JavaScript** Data privacy *To remember values *To avoid global variables *To maintain state *For callbacks and timers Data Privacy (Real-World Example: Password): We use closures to hide private data. function createPassword () { let password = " 12345 " ; return function () { console . log ( password ); }; } const getPassword = createPassword (); getPassword (); // 12345 Maintaining State (Real-World Example: Counter) Closures help to remember previous
Continue reading on Dev.to Webdev
Opens in a new tab


