JAVASCRIPT CLOSURES ??

JAVASCRIPT CLOSURES ??

"Closure is a very confusing concept in JavaScript. In this series of posts, I will try to explain closures in JavaScript and their applications."

In JavaScript, a closure is like a secret compartment inside a function that can remember things even after the function has finished running.

Imagine you have a backpack with a zipper. Inside the backpack, you put a few things like a book and a pencil. When you close the backpack zipper, you can't see what's inside anymore. But, you still remember what's inside because you put those things in there.

In the same way, when a JavaScript function runs, it can create a secret compartment (which is the closure) where it can store some values. Even after the function finishes running, the closure still remembers those values.

So, just like you can open your backpack later and see what's inside, another function can access the closure and see what values are stored inside.

Imagine you have a function called addNumber, which takes in a number and returns a new function. The new function takes in another number and adds it to the number passed into addNumber.

Here's the code:


function addNumber(num1) 
  return function(num2) {
    return num1 + num2;
  }
}

const addFive = addNumber(5);
console.log(addFive(3)); // Output: 8{        

Here are some applications of Closures in Javascript:

1) Private variables and functions: JavaScript closures can be used to create private variables and functions that are hidden from the global scope. This can help to prevent accidental modification or access of these variables or functions from other parts of the program.

2) Event handlers: Closures are commonly used in event handlers to retain access to variables that are outside the scope of the event handler function. For example, a click event handler might use a closure to remember the value of a counter variable so that it can increment it each time the button is clicked.

3) Caching: Closures can be used to create a cache of frequently used data. For example, a function that generates random numbers might use a closure to remember the last few numbers it generated, so that it can avoid repeating them.

1) Private variables and functions

When we talk about private variables and functions in JavaScript, we mean variables and functions that are hidden from the global scope. That means that they can only be accessed from within a specific function, and not from outside that function.

Let's imagine that you have a toy box with a lock on it. The toy box is like a function, and the lock is like a closure. The closure can remember the code inside the function and keep it hidden from the outside world.


function createCounter() 
  let count = 0; // this variable is private and can only be accessed within the createCounter function

  return function() {
    count++;
    console.log(count);
  };
}

const counter = createCounter();
counter(); // Output: 1
counter(); // Output: 2{        

2) Application of Closures in Event Handling

In JavaScript, event handlers are functions that are called when a specific event occurs, like a button click or a key press. When an event handler function is called, it might need access to some variables that are outside of its own scope. This is where closures come in handy.

Imagine that you're playing a game on your computer, and you need to keep track of the number of points you've scored. The game has a button that you click to score points. When you click the button, an event handler function is called.

In the example below, we have a variable called score that's outside the scope of the event handler function clickHandler. When the button with the ID score-button is clicked, the clickHandler function is called, and it increments the score variable using the closure.

So, each time you click the button, the clickHandler function is called, and the closure remembers the value of score. The function logs the updated score to the console.

In this way, closures can be used in event handlers to retain access to variables that are outside the scope of the event handler function.

let score = 0; // this variable is outside the scope of the event handler functio


function clickHandler() {
? score++; // the closure remembers the value of the score variable
? console.log("Score:", score);
}


document.getElementById("score-button").addEventListener("click", clickHandler);        

3) Caching

Caching is a technique that's used to store data that's frequently accessed, so that it can be retrieved more quickly the next time it's needed. This can make programs run faster and more efficiently.

Imagine that you're playing a game on your computer that involves generating random numbers. Generating random numbers can be slow, so you want to use caching to make the game run more smoothly.

In the picture there is a function that generates random numbers using a closure to cache the last few numbers:

In the example below, the generateRandomNumber function creates a private array called lastNumbers that can only be accessed from within the generateRandomNumber function. The function returns another function that generates a random number and adds it to the lastNumbers array. If there are more than three numbers in the array, the oldest number is removed.

When we call generateRandomNumber, it returns a new function, which we store in a variable called randomNumber. We can then call the randomNumber function multiple times to generate random numbers. The closure remembers the value of lastNumbers, so that we can see the last few numbers that were generated.

In this way, closures can be used to create a cache of frequently used data, like random numbers.

function generateRandomNumber() 
? let lastNumbers = []; // this array is private and can only be accessed within the generateRandomNumber function


? return function() {
? ? let randomNumber = Math.floor(Math.random() * 10) + 1; // generates a random number between 1 and 10
? ? lastNumbers.push(randomNumber); // adds the new random number to the array
? ? if (lastNumbers.length > 3) {
? ? ? lastNumbers.shift(); // removes the oldest number from the array if there are more than 3 numbers
? ? }
? ? console.log("Last numbers:", lastNumbers); // logs the last few numbers to the console
? ? return randomNumber;
? };
}


const randomNumber = generateRandomNumber();
console.log(randomNumber()); // Output: 2
console.log(randomNumber()); // Output: 7
console.log(randomNumber()); // Output: 5
console.log(randomNumber()); // Output: 2

{        

Remember that closures are an important tool in JavaScript that can help you write more flexible, modular code.

Keep practicing and experimenting with closures in your own projects to get a better feel for how they work and how you can use them to solve problems.

要查看或添加评论,请登录

Salman Ullah Khan的更多文章

  • The Future of Work: Trends to Watch Out For

    The Future of Work: Trends to Watch Out For

    The world of work is changing rapidly, and it can be challenging to keep up with the latest trends and technologies…

社区洞察

其他会员也浏览了