Modules

Node.js developers are already familiar with working with modules by using the require statement (CommonJS modules). There is also another popular JavaScript standard for modules which is the Asynchronous Module Definition (AMD). RequireJS is the most popular AMD implementation. ES2015 introduced an official module feature in the JavaScript specification. Let's create and use some modules.

The first module we will create contains two functions to calculate the area of geometric figures. In a file (17-CalcArea.js), add the following code:

const circleArea = r => 3.14 * (r ** 2); 
 
const squareArea = s => s * s; 
 
export { circleArea, squareArea }; // {1} 

This means we are exposing both functions so other files can use them ({1}). Only ...

Get Learning JavaScript Data Structures and Algorithms - Third Edition now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.