Back to articles
JavaScript Closures Explained Simply

JavaScript Closures Explained Simply

via Dev.toKathirvel S

Let’s be honest. Closures in JavaScript sound scary at first. You’ve probably seen definitions like: “A closure is a function that retains access to its lexical scope…” And your brain immediately goes: Nope. But here’s the truth — closures are not complicated. You’re already using them. You just don’t realize it yet. So let’s break it down slowly, clearly, and in a way that actually sticks. First — don’t scroll Look at this code. function outer () { let name = " Alex " ; return function inner () { console . log ( name ); }; } const fn = outer (); fn (); What do you think the output is? Don’t skip. Think. . . . Now imagine you bet money on your answer. Output: Alex If that surprised you even a little… good. You’re in the right place. Now here’s the real question Why is name still available? outer() is already done. Gone. Finished. So why didn’t name disappear with it? If your answer is: “Because JavaScript is weird” No. That’s just avoiding the truth. Or worse — memorizing without under

Continue reading on Dev.to

Opens in a new tab

Read Full Article
9 views

Related Articles