DEV Community

loading...

An Example of a Closure in JavaScript

Nevin Katz
I am a web and app developer who writes about programming, tech tools, and my experiences building things. By day, I work at Education Development Center.
Updated on ・2 min read

Hi everyone,

The concept of the closure is one of the tougher concepts for me when I first started learning JavaScript in depth. If you are new to the concept, a closure is essentially a function bundled together with its surrounding state, which typically includes variables that the closure needs. A closure is typically a function within a larger function, which serves as a "bubble." All the variables within this larger function bubble are only accessible by methods in the closure.

The JavaScript engine is smart enough to realize that the variables are needed, so the engine's garbage collector does not obliterate them.

Below is a quick example of an object with four functions that are actually closures.

get, set, increment, and reset. They all act on a variable called count, which sits within the immediately invoked function expression (IIFE) holding the closure.

Each function, which comes bundled with its surrounding environment, is a closure.

  • the get method will simply get the count value.

  • the set method sets the count value to any value we want.

  • the increment method will increment the existing value by the amount passed in as a parameter. If no value is passed in, it increments the value by 1.

  • the reset method resets the value to zero.

These methods are the only way the user can access the count value. In this way, the use of a closure causes the count value to act in a similar way to that of a private variable in a Java object; it cannot be accessed outside the object, so methods are required to retrieve its value or update it.

In the demo, you will see that an init method grabs some references to the HTML elements we print to and then calls all the methods. Take a look at how they are called and see if you can understand what causes these particular values to be printed out.

I hope this quick post gives you a solid idea of what closures are about. Thanks for reading!

Elsewhere

For a tutorial on closures with an easy on-ramp, check out JavaScript Closures and Their Scope Bubbles on Medium.

Discussion (8)

Collapse
lukeshiru profile image
LUKESHIRU

From my point of view, closures are difficult to understand if you have previous experience with languages that don't have closure on them. If your first programming language already has closure, is almost obvious that something defined in the upper scope is available to the inner scope, and that doesn't apply the other way around:

define A;
define B;

function (argument C) {
  define D;
  // A, B, C and D are all available here.
}

// Only A and B are available here
Enter fullscreen mode Exit fullscreen mode

That pseudocode is something that we can see in any language that has closure, but in other (generally older) languages, the experience is actually less intuitive:

define A;
define B;

function (argument C) {
  define D;
  // Only C and D are available here ????
}

// Only A and B are available here
Enter fullscreen mode Exit fullscreen mode

If you think about it, closure makes way more sense than the languages that don't have it:

  ┌────────────┐
  │ A, B       │
  │  ┌──────┐  │
  │  │      │  │
  │  │ C, D │  │
  │  │      │  │
  │  └──────┘  │
  └────────────┘
Enter fullscreen mode Exit fullscreen mode

Maybe you can confirm it for me, but you previously had experience with a language that didn't had closures on it, right?

Collapse
nevkatz profile image
Nevin Katz Author • Edited

If you count learning BASIC when I was twelve, then that's right, it didn't have closures. At least none that I know of. Mainly a lot of GOTO statements. :) My next language was ActionScript -- It had closures but I never used them.

So yes, my mental template did not have closures in it initially, so that may be why I found it hard to wrap my head around them. I really appreciate your examples here - they are quite illuminating.

Collapse
lukeshiru profile image
LUKESHIRU

My first programming language was Pascal, followed by C and C++ ... you can "mimic" closures on them, but they are pretty much non-existent. I remember clearly that all those languages behave kinda unexpectedly when I was learning them. When I started doing JS and learn about closures, I was happy to find a language that did what I was expecting all along 🤣

Thread Thread
nevkatz profile image
Nevin Katz Author

Ha! Finally! Very interesting to hear about how these other languages handle closures. Thanks for sharing!

Collapse
jcubic profile image
Jakub T. Jankiewicz

This is not a closure with four methods, but object with 4 closures. Closure if a function with enclosing environment.

Collapse
nevkatz profile image
Nevin Katz Author • Edited

Thanks, Jakub. I updated this post as well as my Medium article to reflect this.

Collapse
wagyourtail profile image
wagyourtail

Why use over classes?

Collapse
nevkatz profile image
Nevin Katz Author

There may not be a reason to if classes do what you need them to. That said I think it is important to be able to recognize closures in a codebase you end up working with. I myself am interested in starting to use JavaScript class syntax so I'll keep this question in mind.