DEV Community

Cover image for I’m Understanding JavaScript Closures: A Beginner's Guide
Krushna Sananse
Krushna Sananse

Posted on

I’m Understanding JavaScript Closures: A Beginner's Guide

What is a Closure?
In JavaScript, a closure is a function that "remembers" its lexical scope, even when the function is executed outside that scope. Simply put, closures allow a function to access variables from its outer (enclosing) function even after that outer function has finished execution.

Closures are a fundamental concept in JavaScript, and understanding them can help you write more efficient and cleaner code. Let’s break it down with an example.

Example of a Closure
Let’s consider the following code:

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

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

  return innerFunction;
}

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

Enter fullscreen mode Exit fullscreen mode

Here’s what happens:

  1. outerFunction creates a local variable outerVariable and an inner function innerFunction.
  2. When we return innerFunction from outerFunction, it "remembers" the scope of the outer function, which includes access to outerVariable.
  3. Even though outerFunction has finished executing, innerFunction still has access to outerVariable because of the closure.

How Does a Closure Work?
A closure is formed when:

  • A function is defined inside another function.
  • The inner function tries to access variables from its outer function’s scope.

The key takeaway is that the inner function "remembers" the environment in which it was created, even after the outer function has returned.

Real-World Example: Creating a Counter
Closures are commonly used in JavaScript to create private variables or to implement functionalities like counters.

Here’s a real-world example of a counter using a closure:

function createCounter() {
  let count = 0;

  return {
    increment: function() {
      count++;
      console.log(count);
    },
    decrement: function() {
      count--;
      console.log(count);
    }
  };
}

const counter = createCounter();
counter.increment();  // Output: 1
counter.increment();  // Output: 2
counter.decrement();  // Output: 1

Enter fullscreen mode Exit fullscreen mode

In this example:

  • createCounter returns two functions: increment and decrement.
  • These functions have access to the count variable, which is "private" to createCounter. The closure allows us to modify and track the count without exposing the variable directly.

Why Are Closures Important?
Closures are useful in JavaScript for:

  • Data encapsulation: They allow private variables that cannot be accessed or modified from outside.
  • Maintaining state: You can use closures to maintain the state of variables across multiple function calls (like counters, timers, etc.).
  • Callback functions and event handlers: Closures are widely used when working with callbacks or event listeners, as they allow access to variables from the parent function even after the event occurs.

Learn More About Closures
If you'd like a more detailed explanation and examples of closures, I’ve created an Instagram video where I break down this concept with some practical examples. Check it out here:Instagram Video on Closures.

Also, be sure to follow me on Instagram for more coding tips, tutorials, and behind-the-scenes content: @thecoddingstack.

Conclusion
JavaScript closures are an essential concept that you'll encounter often while coding. They allow for powerful, flexible programming patterns that help you keep your code clean and maintainable. With the knowledge of closures, you’ll be able to better manage state, create private variables, and build more complex applications.

JavaScript #Closures #WebDevelopment #CodingForBeginners #LearnJavaScript #ProgrammingLife #FrontendDeveloper #TechTips #CodeNewbie #TheCoddingBachelor

Top comments (0)