Many developers use the module pattern which is based on JavaScript closures. You can read more about the module pattern in depth here, but I'm going to cover the basics and how it implements closures. The purpose of using the module pattern is to organize code, keep the global scope clean, and keep private code that shouldn't be accessible from outside of the module. The module pattern looks like this:

var module = (function(){ var localVar = 1913; var localFunc = function() { return localVar; } var otherLocalFunc = function(num) { localVar = num; } return { getVar: localFunc, setVar: otherLocalFunc } })();

Here we are creating a single environment inside of an anonymous function. This environment contains a local variableand a local function expression. Neither of these variable names are accessible from outside of our anonymous function thus keeping the global namespace clean. In order to access anything from outside our anonymous function, it needs to be returned by the anonymous function.

As you can see in our example, we are returning an object with a key of getVar that is set to the value of localFunc and another key of setVar which is set to the value of otherLocalFunc. The beautiful thing about this pattern is that the state of the module persists throughout the life of our application. By this, I mean that even though localVar is not directly accessible from the outside, the functions we return still have access to this variable.

Take a look at this example utilizing the code from above:

console.log(module.getVar()); > 1913 module.setVar(1776); console.log(module.getVar()); > 1776

We've successfully emulated a private variable, localVar, in JavaScript. We've kept the global namespace clean, the only global variable here is module. And we've done this all using a closure. Although this is not part of the scope of this guide, this pattern depends on an IIFE (immediately invoked function expression). You'll notice that the anonymous function is wrapped in parenthesis like this (function() { ... })(). Without the parenthesis, this would simply be a function definition. But adding the parenthesis (notice the trailing parenthesis as well) causes this to become a function expression that is invoked immediately. Read more about this here.