Closures in JavaScript - the Simplest Explanation

Read Time:2 Minute, 22 Second

Closures in JavaScript are like secret passageways for a function to remember certain variables, even after it’s done running. In this article, I’ll try to answer the question “how do JavaScript closures work?” in the simplest way so you can start using them right away.

Before we move on, remember you can unlock the full potential of your website development by using DoTenX, an open-source platform that allows you to create professional-grade websites, landing pages, APIs, and more. Take advantage of DoTenX’s powerful tools and capabilities by visiting the repository at github.com/dotenx/dotenx today!


Let’s say you want to create a simple counter, but you don’t want other parts of your code to mess with the counter’s internal number. You can create a function that returns an object with methods that can change the internal number, but only the function knows about it. Here’s an example:

function counter() { let count = 0; return { increment: function() { count++; }, decrement: function() { count--; }, getCount: function() { return count; } };
} let myCounter = counter();
console.log(myCounter.getCount()); // 0
myCounter.increment();
console.log(myCounter.getCount()); // 1
Enter fullscreen mode Exit fullscreen mode

In our example, you could say the counter function returns an object with three methods: increment, decrement, and getCount.

Each of these methods have access to the count variable, which is defined within the parent counter function. But, because the counter function has completed execution, the count variable is not directly accessible from the global scope while the inner functions still have access to it.

In other words, the returned object and its methods are closures that have access to the count variable.

So, this was one of the common use cases of closures and now let’s take a look at another example.

Another common use case for closures is to create a function that we want to pass as a callback and maintain access to variables in its parent scope. For example, take a look at this code:

function createFullName(firstName) { return function(lastName) { return firstName + " " + lastName; };
} let myFullName = createFullName("John");
console.log(myFullName("Doe")); // "John Doe"
console.log(myFullName("Smith")); // "John Smith"
Enter fullscreen mode Exit fullscreen mode

In this overly simplified example, we have a function createFullName that takes a person’s first name as an argument and returns a new function which itself takes a person’s last name as an argument and returns the full name.

The inner function is a closure because it “closes over” the firstName variable and remembers it, even though the parent function has finished running. This can be useful for example in a form where user fills first name and last name in two different inputs.

This technique is also one of the fundamentals of functional programming in JavaScript.

Can you add any other use cases or examples?

Source: https://dev.to/mohsenkamrani/closures-in-javascript-the-simplest-explanation-9gj

CyberSEO Pro - OpenAI GPT-3 autoblogging and content curation plugin for WordPress

Tag Cloud

Java Java Logical Programs OTP Generation in Java python Recursion youtube video ASCII Upper and Lower Case blockchain javascript graph learn to code software development Successful Software Engineers breadth first search Java Array Programs Java Programs Uncategorized android ios programming kotlin web-development django data sql cybersecurity database swiftui serverless aws swift rust react background-position gradients loader mask grid nth-child pseudo elements indieweb WordPress Print Array without brackets C++ factorial Java String Programs Final Keyword Static Variable Axie Infinity Cryptokitties NFT games tool inserting MISC Tips Codes python code python projects python3 system info python project Bigginers How to Do Integrations Payment Gateways PHP checkout page in php Implement stripe payment gateway in Step by step in PHP integrate stripe gatway in php mysql payment gateway integration in php step by step payment gateway integration in php step by step with source code payment gateway integration in website PHP Integrate Stripe Payment Gateway Tutorial PHP shopping cart checkout code shopping cart in php stripe php checkout PHP/MySQL/JSON best international payment gateway does google pay accept international payments how to accept international payments in india paytm payment gateway razorpay codeigniter github razorpay custom checkout github razorpay get payment details razorpay integration in codeigniter github razorpay international payments Razorpay payment gateway integration in CodeIgniter razorpay payment gateway integration in php code Razorpay payment gateway integration with PHP and CodeIgniter Razorpay payment gateway setup in CodeIgniter Library & Frameworks Tips & Tricks UI/UX & Front-end coding birds online html code for google sign in login with google account in PHP login with google account using javascript login with google account using javascript codeigniter login with google account using php login with google account using php source code
Meme Monday 🫵 Previous post Meme Monday 🫵
Trouble at the docks – part 1 Next post Trouble at the docks – part 1

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.