What are closures? Learn with Real World Example

What are closures? Learn with Real World Example
February 01, 2023

A closure in JavaScript is a special type of function that keeps track of variables and information from the outside, or "enclosing", function even after it has finished running.

This allows the inner function to continue to use and reference these values, even after the outer function has completed its execution.

Closures are a useful tool for creating private variables and generating functions with specific attributes.

For example, let's consider a website where a user can click on different buttons to change the background color of the page.

Without using closures, you would need to create a separate function for each button to handle the click event and change the background color, like this:

Code without closure:

function changeBackgroundToRed()
{
  document.body.style.backgroundColor = 'red';
}

function changeBackgroundToGreen()
{
  document.body.style.backgroundColor = 'green';
}
document.getElementById('red-button').addEventListener('click', changeBackgroundToRed);
document.getElementById('green-button').addEventListener('click', changeBackgroundToGreen);


Code with closures:

function changeBackgroundColor(color) {
  return function() {
    document.body.style.backgroundColor = color;
  };
}

document.getElementById('red-button').addEventListener('click', changeBackgroundColor('red'));

document.getElementById('green-button').addEventListener('click', changeBackgroundColor('green'));


Let's understand the code:

In this example, the changeBackgroundColor function acts as a function factory, generating a new function for each button that has the desired background color "closed over" within its scope.

This way, when the generated function is executed, it has access to the correct background color value, even though the changeBackgroundColor function has already returned.


Resources for You

ChatGPT Guide For Software Developers

Learn to use ChatGPT to stay ahead of competition

Front-End Developer Interview Kit

Today, Start preparing to get your dream job!

JavaScript Developer Kit

Start your JavaScript journey today!

Master JavaScript by Solving Daily Challenges

Challenge Yourself Daily: Advance Your JavaScript Skills and Career

View Challenges

Newsletter for Developers!

Join our newsletter to get important Web Development and Technology Updates