# Libraries via closures in JavaScript

Often they create JavaScript libraries, which are collections of functions for other programmers to use.

Such libraries are usually wrapped into modules using closures. This is done so that when the library is linked, as few functions as possible appear in the outside evironment.

As a rule, each library tries to create only one variable in the outside environment - an object with library functions. At the same time, inside the library code, some of the functions are basic, and some are helper. Obviously, we want to export only the necessary functions to the outside environment, without littering the exported object with helper functions.

Let's look at an example. Suppose we have the following set of functions that we would like to turn into a library:

`function square(num) { return num ** 2; } function cube(num) { return num ** 3; } function avg(arr) { return sum(arr, 1) / arr.length; } function digitsSum(num) { return sum(String(num).split('')); } // helper function function sum(arr) { let res = 0; for (let elem of arr) { res += +elem; } return res; }`

Let's make our functions look like a module:

`;(function() { function square(num) { return num ** 2; } function cube(num) { return num ** 3; } function avg(arr) { return sum(arr, 1) / arr.length; } function digitsSum(num) { return sum(String(num).split('')); } // helper function function sum(arr) { let res = 0; for (let elem of arr) { res += +elem; } return res; } })();`

And now we export all functions, except for the helper one:

`;(function() { function square(num) { return num ** 2; } function cube(num) { return num ** 3; } function avg(arr) { return sum(arr, 1) / arr.length; } function digitsSum(num) { return sum(String(num).split('')); } // helper function function sum(arr) { let res = 0; for (let elem of arr) { res += +elem; } return res; } window.math = {square, cube, avg, digitsSum}; })();`

Let's say we have an `index.html` HTML page :

`<html> <head> <script> </script> </head> </html>`

Let's link our library to it:

`<html> <head> <script src="math.js"></script> <script> </script> </head> </html>`

Let's use functions from our library:

`<html> <head> <script src="math.js"></script> <script> alert(math.avg([1, 2, 3]) + math.square()); </script> </head> </html>`

Given the following code:

`function avg1(arr) { return sum(arr, 1) / arr.length; } function avg2(arr) { return sum(arr, 2) / arr.length; } function avg3(arr) { return sum(arr, 3) / arr.length; } // helper function function sum(arr, pow) { let res = 0; for (let elem of arr) { res += elem ** pow; } return res; }`

Make this code in the form of a module. Export all functions except the helper one to the outside.

Study the underscore library. Make your own similar library by repeating `5`-`10` functions of the original library in it.

←
↑
en ru