/
/
Closures in JavaScript: what, why, and how?
Share on facebook
Share on twitter
Share on linkedin
Share on whatsapp
Share on email

Closures in JavaScript: what, why, and how?

In this blog post, we’ll discuss what closures are, wh they’re powerful, and how they can be applied when writing JavaScript code with access to external APIs like databases or third-party libraries. We’ll also demonstrate some practical examples that utilize closures using code snippet examples.

🎁 Where are closures used in JavaScript?

Closures are one of those concepts that many struggles to get their heads around in javascript. Basically, closures are like little packages of functions that carry information about their surroundings. Closures, also known as lexical or function closures. In other words, closure gives you access to an outer function’s scope from an inner function outside of its original usage.

🎁 Why do we need JavaScript closures?

Closures are a powerful and unique feature of JavaScript. They allow you to capture the state of variables in one context, then use them in another. This is useful for scenarios such as asynchronous code where it’s impossible to pass values via arguments or return statements. Closures are also used heavily with ReactJS, making them important for developers who work on front-end applications.

// 🎁 A simple example for understanding closures 🎁
const adder = (firstNum) => {
    const add = (secondNum) => console.log(firstNum + secondNum);
    return add;
};

const addSeven = adder(7);
addSeven(10); // Output: 👉 17

const addFive = adder(5);
addFive(100); // Output: 👉 105

🎁 What is closure in JavaScript example?

The adder function returns the add function but doesn’t invoke it (add()). This indicates that when we invoke the adder with a firstNum argument (const addSeven = adder(7)), it returns a function that now knows what the value of firstNum is, and we can invoke it (addFive(7)) to get the final result.

// 🎁 A real-life example of closures in production code 🎁
const dataFetcher = (url) => {
    return async function getData(path) {
        try {
            const endpoint = path ? `${url}/${path}` : url;
            const res = await axios.get(endpoint);
            return res.data;
        } catch (error) {
            console.log(error);
        }
    };
};

const getUserDataFetcher = async (path) => {
    try {
        const users = dataFetcher('https://jsonplaceholder.typicode.com/users');
        const usersData = await users(path);
        console.log(usersData);
    } catch (error) {
        console.log(error);
    }
};

//📍Gets the entire users list
getUserDataFetcher(); // Output: 👉(5) [Object, Object, Object, Object, Object]

//📍Gets the to do with id: 1
getUserDataFetcher('1'); // Output: 👉 {id: 1, name: "Lean Jen", username: "Brt"}

//📍Gets the to do with id: 4
getserDataFetcher('4'); // Output: 👉 {id: 4, name: "Joe Leb",username: "Leb"}

Conclusion 🎁

As you can see, closures are a powerful tool in JavaScript. They allow for encapsulation of data and logic inside self-contained units that can be passed around the application as needed. Closures help keep code modularized and organized while also making it more readable. I hope this post was helpful to anyone who wanted to learn about what closures are, why they’re used, and how we use them!

Recent Snippet

How to use reduce over an array of objects

To get the maximum or the minimum value from an array, we can use Math.max() and pass as arguments the numbers from which we want to pick.

How to get the highest or the lowest value in an array

To get the maximum or the minimum value from an array, we can use Math.max() and pass as arguments the numbers from which we want to pick.