DEV Community

Cover image for Closures - JavaScript
Muhammad Shakir
Muhammad Shakir

Posted on

Closures - JavaScript

Let's explore a fascinating concept in JavaScript called closures. Think of them as special coding tools that remember important things, much like a magical vault that keeps valuable information safe even after its owner has left. Just as a chef's recipe book holds onto the memory of ingredients long after the meal is cooked, closures in JavaScript have the ability to remember important data. We'll take a journey through real-life examples to help you understand closures easily, even if English isn't your first language.

Understanding Closures in JavaScript with Practical Examples

Closures might sound complicated, but they're really just like helpful friends that remember things for us. They're used in coding to make tasks easier. Imagine two everyday situations: cooking and handling money. These scenarios will show you how closures work, step by step.

Scenario 1: The Cooking Connection

Imagine you're a chef in your kitchen, creating delicious dishes. You have a magical cookbook that not only guides you through recipes but also remembers all the ingredients you use. Even after you've finished cooking, the cookbook holds onto the memory of what you've added. Closures work in a similar way. They're like little assistants that remember things from the past, even when that time is over.

Cooking Scenario Code:

function prepareDish(dishName) {
    const ingrediants=[];
    function addIngrediants(ingrediant) {
        console.log(`${ingrediant} added to ${dishName}`);
    return addIngrediants;

const preparePasta = prepareDish("Pasta");
const prepareSoup=prepareDish("Soup");

preparePasta("Pasta Noodles");
prepareSoup("Tomato Souce")

preparePasta("Chicken Broth");
Enter fullscreen mode Exit fullscreen mode

The Output of the above Code will be as follows:

Pasta Noodles added to Pasta
Tomato Souce added to Soup

Chicken Broth added to Pasta
Carrots added to Soup

Scenario 2: The Money Manager

Now, let's switch to a different scene - managing money. Imagine you're a manager in a company, keeping track of employee salaries. You write down what each employee earns and then calculate the total amount. Just like in the cooking scenario, closures are at work here. They help functions remember important details, even after they've done their main job.

Money Scenario Code:

function createSalaryTracker() {
  let salaries = [];
  function addSalary(employee, amount) {
    salaries.push({ employee, amount });
    console.log(`Added ${amount} salary to ${employee}'s account`);

  function calculateTotalSalary() {
    let total = 0;
    for (let record of salaries) {
      total += record?.amount;
    return total;

  return {

const salaryTracker = createSalaryTracker();
salaryTracker.addSalary("Alice", 50000);
salaryTracker.addSalary("Bob", 25000);

const totalSalary = salaryTracker.calculateTotalSalary();

console.log(`Total Salary: ${totalSalary}`);

Enter fullscreen mode Exit fullscreen mode

The Output of the above code will be as follows:

Added 50000 salary to Alice's account
Added 25000 salary to Bob's account

Total Salary: 75000

The Magic of Closures:
In both scenarios, closures help functions remember things. Just like your magical cookbook holds onto ingredients, closures remember data even after their main task is done. This is like having a memory in coding!

Closures might sound tricky, but they're actually very helpful. They're like small assistants that remember important stuff for us. So, whether you're cooking or managing money, closures are there to make things easier in the world of coding.

Top comments (5)

citronbrick profile image

You can enable syntax highlighting in using

(triple backtick) javascript
(triple backtick)

chaitanya-kaushal profile image

The content is well-knitted and easy to understand.

prodevxpert profile image
Muhammad Shakir

Thanks for the Good wrods ❤

aaronplate profile image
Aaron Nuñez

His behavior seems like a class 👍

prodevxpert profile image
Muhammad Shakir

Your kind words boosted my motivation. Thanks man