Creating an ES module in JavaScript

Now let's start learning about modules. Each module must be a separate file. The variables and functions that we place in this file will not be accessible from outside the file. This is the advantage of modules - we can create any variables and functions without fear of conflict with names from other libraries.

Those variables and functions that we want to make visible from the outside, we must export using the export command.

Let's try with an example. Let's create the math module that will provide a library of functions for mathematical operations.

Let's place our module in the math.js file and make several functions in it:

function root2(num) { return round(num ** (1 / 2)); } function root3(num) { return round(num ** (1 / 3)); } function round(num) { return num.toFixed(2); }

Let the functions for extracting roots be the main ones and will be exported to the outside, and the function for rounding will be auxiliary and will not be exported. Let's write the export command to necessary functions:

export function root2(num) { return round(num ** (1 / 2)); } export function root3(num) { return round(num ** (1 / 3)); } function round(num) { return num.toFixed(2); }

Create a module containing the function pow2 to raise a number to the second power, pow3 to raise to the third, and pow4 to raise to the fourth.

enru