Modules using closures in JavaScript

The problem described above is typical for any programming language. The so-called modules are used as a solution.

A module is a kind of construction, made in such a way that the variables and functions of this construction are visible only inside it and don't interfere with anyone outside.

There are several types of modules in JavaScript. The simplest - modules via closures are created by in-place function call, like this:

;(function() { // here is a module code })();

Variables and functions created in such a module will not be visible outside of that module:

;(function() { let str = 'a module variable'; function func() { alert('a module function'); } })(); // Here the variables and functions of the module are not available: alert(str); alert(func);

Practical usage

Let we have two divs with numbers:

<div id="div1">10</div> <div id="div2">10</div>

Let's make it so that on click on the first div, its value is squared, and on click on the second div, its value is cubed.

Let's organize our code in the form of two modules:

;(function() { let elem = document.querySelector('#div1'); // the first div function func(num) { return num * num; // let's square } elem.addEventListener('click', function() { this.textContent = func(elem.textContent); }); })(); ;(function() { let elem = document.querySelector('#div2'); // the second div function func(num) { return num * num * num; // let's cube } elem.addEventListener('click', function() { this.textContent = func(elem.textContent); }); })();

Now in each of the modules we can use any variables and functions without fear that they will conflict with other variables and functions of our script.

For example, we store both elements in the variable elem - each in its own variable of its module. If modules were not here, we would have to introduce different variables to store our elements. And with modules, we can safely use our variable without fear that someone will also want to use this variable.