Menu

Post image 1
Post image 2
1 / 2
0

JavaScript Closures Explained Like You're Learning Them for the First Time

DEV Community: frontend·Anshul Sharma·2 days ago
#8iSby9Gc
#dev#fullscreen#enter#exit#function#article
Reading 0:00
15s threshold

JavaScript Closures Explained Like You're Learning Them for the First Time Have You Ever Wondered How This Works? Imagine you have a function: function createCounter () { let count = 0 ; return function () { count ++ ; console . log ( count ); }; } const counter = createCounter (); counter (); counter (); counter (); Enter fullscreen mode Exit fullscreen mode Output: 1 2 3 Enter fullscreen mode Exit fullscreen mode At first glance this looks strange. The variable count belongs to createCounter() . Once createCounter() finishes executing, shouldn't count disappear? Then why does JavaScript still remember it? The answer is: Closures. But before understanding closures, let's understand how variables normally behave. How Variables Normally Work Consider this function: function greet () { let name = " Anshul " ; console .…

Continue reading — create a free account

Join HashtagPLUS to read full articles, follow hashtags, vote, and join the conversation.

Read More