Blog/NotesConcept

Master Closures in JavaScript with 5 practical examples

Explore the 5 practical examples to understand closures in JavaScript that can help to use closures in the application confidently.

Intermediate

Anuj Sharma

Last Updated Feb 17, 2026


Master Closures in JavaScript with 5 practical examples

Understanding closures in JavaScript is crucial for frontend developers as they play a significant role in how functions work and interact with variables. This is one of the confusing topics with so many applications in different contexts.

In this blog post, we will explore 5 practical examples to help you grasp the concept of Closures in JS and use them confidently in your applications.

What are Closures in JavaScript?

In JavaScript, a closure is a combination of a function bundled together with references to its surrounding state (the lexical environment). This means that a closure gives you access to an outer function's scope from an inner function. Here is a simple example.

function outerFunction() {
    let outerVariable = 'I am from the outer function';

    function innerFunction() {
        console.log(outerVariable);
    }

    return innerFunction;
}

const innerFn = outerFunction();
innerFn(); // Output: I am from the outer function

5 Practical Closures Example in JavaScript

Example 1: Basic Closure

In this example, the inner function has access to the outerVariable defined in the outer function, demonstrating how closures work.

Example 2: Closures in Event Listeners

function addClickListener() {
    let count = 0;

    document.getElementById('clickMeButton').addEventListener('click', function() {
        count++;
        console.log('Button clicked ' + count + ' times');
    });
}

addClickListener();

Here, the closure maintains access to the count variable across multiple click events, incrementing it each time the button is clicked.

Example 3: Closures in Asynchronous Operations

function delayedGreeting() {
    let name = 'Alice';

    setTimeout(function() {
        console.log('Hello ' + name);
    }, 2000);
}

delayedGreeting();

This example showcases how closures capture the name variable even after the outer function has finished executing, allowing the delayed function to access it.

Example 4: Closures with Higher-Order Functions

function multiplier(factor) {
    return function(number) {
        return number * factor;
    };
}

const double = multiplier(2);
console.log(double(5)); // Output: 10

By returning a function inside another function, closures enable the creation of functions that remember and use the variables from their lexical environment.

Example 5: Closures for Data Privacy

function createCounter() {
    let count = 0;

    return {
        increment: function() {
            count++;
        },
        getCount: function() {
            return count;
        }
    };
}

const counter = createCounter();
counter.increment();
console.log(counter.getCount()); // Output: 1

This example demonstrates how closures can be used to encapsulate and protect data, providing a way to maintain private variables within a function.

Best Practices for Using Closures

  • Understand the scope chain to avoid unexpected behaviour.
  • Avoid creating unnecessary closures to prevent memory leaks.
  • Use closures for encapsulation and data privacy when needed.
  • Consider performance implications when using closures in performance-critical code.

Final thoughts

Closures are a powerful feature in JavaScript that can be leveraged to write more concise and efficient code. By mastering closures, you can enhance your understanding of functions and scope in JavaScript.

Understanding different use cases of closures in JavaScript helps to easily answer closure-related questions in the frontend interview and also helps in day-to-day frontend development work.

Further Reading

  1. Checkout best resources for Closures in JavaScript
  2. Top Interview JavaScript Questions & Answers

Love this Blog? Share it Now!

Help others discover this resource

About the Author

Anuj Sharma

A seasoned Sr. Engineering Manager at GoDaddy (Ex-Dell) with over 12+ years of experience in the frontend technologies. A frontend tech enthusiast passionate building SaaS application to solve problem. Know more about me  🚀


Learn Next

Featured

20 Most Asked Custom Hooks in React for Interviews

Top 10 React Performance Optimization Techniques25 Top JavaScript Interview Questions for BeginnersHow to create custom useInfiniteScroll Hook in ReactImplement useThrottle Custom Hook In React

Comments

Be the first to share your thoughts!

Guest User

Please login to comment

0 characters


No comments yet.

Start the conversation!

About the Author

Anuj Sharma

A seasoned Sr. Engineering Manager at GoDaddy (Ex-Dell) with over 12+ years of experience in the frontend technologies. A frontend tech enthusiast passionate building SaaS application to solve problem. Know more about me  🚀

Share your expertise

Publish a blog or quick notes on topics you know well — your write-up could be the answer someone needs before their next frontend interview.

Build your portfolio

Help the community

Sharpen your skills

Earn goodies

Other Related Blogs

How to convert HEX to RGB in JavaScript

Anuj Sharma

Last Updated Jul 6, 2026

A quick way to convert HEX to RGB in JavaScript that will help to do the CSS HEX to RGB color conversion programmatically.

How to convert RGB to HEX in JavaScript

Anuj Sharma

Last Updated Jul 6, 2026

A quick way to convert RGB to HEX in JavaScript that will help to do the CSS RGB to HEX color conversion programmatically

Understand Debouncing in JavaScript with Examples

Anuj Sharma

Last Updated Jun 27, 2026

Understand the concept of Debouncing in JavaScript to improve the performance of your web application and optimize the event handling in JavaScript, by limiting API calls or DOM events.

Implement JSON Parse polyfill in JavaScript

Anuj Sharma

Last Updated Jun 15, 2026

Explore the code implementation of JSON Parse Polyfill in JavaScript that can parse a string into valid JSON.

Implement JSON Stringify Polyfill in JavaScript

Anuj Sharma

Last Updated Jun 15, 2026

Explore the detailed explanation of the JSON Stringify Polyfill implementation in JavaScript to prepare for the frontend interviews.

What is javascript:void(0) and How it Works?

Anuj Sharma

Last Updated Jun 15, 2026

A comprehensive explanation about using javascript:void(0) in javascript. When to use javascript:void(0) and how it works with examples of using it with anchor tag.

Understand JavaScript Date Object with Examples (for JavaScript Interviews)

Anuj Sharma

Last Updated Jun 15, 2026

Go through different ways to display dates using javascript date object. It covers examples of date object usage to understand the main concepts of javascript date object.

Apply Polyfill in JavaScript: Step by Step Explanation (For Interview)

Anuj Sharma

Last Updated Jun 15, 2026

Understand how the apply method works in JavaScript and cover step by step-by-step explanation of the apply method polyfill in JavaScript to understand its internal implementation.

Stay Updated

Subscribe to FrontendGeek Hub for frontend interview preparation, interview experiences, curated resources and roadmaps.

FrontendGeek
FrontendGeek

All in One Preparation Hub to Ace Frontend Interviews. Master JavaScript, React, System Design, and more with curated resources.

Consider Supporting this Free Platform

Buy Me a Coffee

Product

HomeFrontend InterviewFrontend JobsQuestionsNewInterview ExperienceBlogsToolsLeaderboardFrontendGeek Chrome extensionGet the extension on the Chrome Web Store →

From Creator

© 2026 FrontendGeek. All rights reserved