Logo

dev-resources.site

for different kinds of informations.

Closures - JavaScript

Published at
8/16/2023
Categories
javascriptclosures
closures
javascript
example
Author
prodevxpert
Author
11 person written this
prodevxpert
open
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) {
        ingrediants.push(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");
prepareSoup("Carrots")
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 {
    addSalary,
    calculateTotalSalary,
  };
}

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!

Conclusion:
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.

closures Article's
30 articles in total
Favicon
Understanding Closures in PHP: Key Differences and Use Cases
Favicon
JavaScript Closures in Depth: Unlocking the Power of Lexical Scope
Favicon
Understanding Closures in JavaScript
Favicon
Mastering Closures and Decorators in Python: From Basics to Advanced
Favicon
Understanding Closure in JavaScript.
Favicon
Let's Understand JavaScript Closures: A Fundamental Concept
Favicon
Memoization in JavaScript
Favicon
Closures: Performance implications
Favicon
Closures: Lifting the hood
Favicon
A Practical Introduction to Closures in JavaScript
Favicon
Unlocking New Possibilities: Rust Compiler Backend Brings Closures to the .NET Universe!
Favicon
πŸ“¦πŸ”“Closures in JavaScript visualized
Favicon
useClosure() {work, backwards in returnValuesAsInput (backwards, work)}
Favicon
Mastering Closures in JavaScript: A Comprehensive Guide
Favicon
# "JavaScript Closures: Demystified."
Favicon
Closures - JavaScript
Favicon
Exploring Advanced JavaScript Techniques: Closures, Prototypes, and Hoisting
Favicon
Unlocking JavaScript Magic: A Beginner's Guide to Closures
Favicon
JavaScript Closures: Understanding the Power of Functions
Favicon
Closures in javascript
Favicon
JavaScript Closure
Favicon
Groovy Gotchas - Loops, Closures, Scope, and Jenkins DSLs
Favicon
Understanding closures in JavaScript
Favicon
Javascript Currying and partials
Favicon
The ultimate explanation of closures
Favicon
Understanding Closures in JavaScript
Favicon
Closures and Memoization
Favicon
A Simple Explanation of JavaScript "Closures"
Favicon
Hoisting with closures example
Favicon
Closures in JavaScript

Featured ones: