Closures are awesome. That’s all you need to know. You’ve just mastered JavaScript. Not really. Keep reading and you’ll understand what I mean.

Programming is all about building blocks, stacking them one by one on top of each other, and the more blocks you have stacked on top of each other, the easier it will be to apply your knowledge to a set of requirements.

When you come across Closures, at first, it’s a bit daunting. Why are there all these parentheses and brackets everywhere. I just want to write some JavaScript. It looks a bit ugly, but once you understand what it’s doing, it’s like an awakening.

What is a closure?

A Closure is an inner function that has access to the outer function’s variables. You can include your own private variable and functions, and only return what’s required to the global namespace. As you can see from the screenshot below, I’ve created a module using a Closure, which allows me to set “privateVar”, and a public function, which is exported into the global namespace, for me to run anywhere else.


var module = (function() {
  var privateVar = "Hello World";

  var publicFunction = function() {
     console.log(privateVar);
   }

  return {
   publicFunction: publicFunction
  };
}());

module.publicFunction(); // Hello World

The highlighted line shows where I’m calling a function that has been returned from the Closure, which logs the value of privateVar to the console.

Understanding how this works is difficult to grasp, but once you do it will open up the big, wide (scary) world of JavaScript to you.

Modular is better

Packaging things up into modules is always going to be beneficial in the long run, whether you’re writing something simple or not. You or someone else is going to have to look at the code you’ve written and figure out why something is broken or they’re trying to add a feature, so organisation of code is a necessity. Closures and modularising code is a great way to do that.

I think Closures also provide the added benefit of having a clean scope with which to test. It encourages testing because you can write to an interface and not an implementation. Abstracting ideas into their simplest forms into modules, and composing functions allows for tests to be written to ensure the longevity of that code.

JavaScript and writing code in general is hard enough. My goal is always to write enough code for it to work, but no more. Closures can help you package things up into reusable functions, requiring different modules as needed.