Passing parameters to a module via closures in JavaScript

It is considered good practice not to hardcode any values into the module, but to pass them as a parameter of the module itself (that is, as a parameter of the function called in-place):

;(function(arg1, arg2) { // the parameters get into variables })(1, 2); // passing some parameters

Let's look at an example. Let's have a div with a number and a button:

<div id="div">3</div> <button id="btn">click me</button>

Suppose we also have some module:

;(function() { let div = document.querySelector('#div'); let btn = document.querySelector('#btn'); function func(num) { return num * num; } btn.addEventListener('click', function() { div.textContent = func(div.textContent); }); })();

As you can see, our element selectors are hardcoded in the module code. A better solution would be to pass them as module parameters - so in the future we can easily change them. Let's refactor our module:

;(function(selector1, selector2) { let div = document.querySelector(selector1); let btn = document.querySelector(selector2); function func(num) { return num * num; } btn.addEventListener('click', function() { div.textContent = func(div.textContent); }); })('#div', '#btn');

Given a button and three inputs into which numbers are entered. On pressing the button print the sum of the entered numbers to the console. Implement a task using a module.

enru