⊗jsPmMCMCU 495 of 502 menu

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.

enru