🎓 A1Learner
🔍
0 of 50 lessons completed

Your Own Module

Your own module is a file you write and share. You write the code, and module.exports shares it.

The module file

This file is math.js. It shares two small functions.

module.exports = {
  add: (a, b) => a + b,
  double: (n) => n * 2
};

Load the module

This line loads math.js. The next line adds 2 and 3.

const math = require("./math.js");
console.log(math.add(2, 3));

Example

const math = require("./math.js");

console.log(math.add(2, 3));
console.log(math.double(4));

Key points

  • Write the functions for one job in one file.
  • module.exports can share more than one function.
  • Share the functions inside one object.
  • require loads the file with ./ and the file name.
  • The result holds the shared functions by name.
  • One module can serve more than one program.

In this example, the first line loads math.js with require. The file math.js shares two small functions. The first print adds 2 and 3. The second print doubles 4.

Note

The file name in require must match the real file name.

Try it Yourself

Edit the code, then press Run.

Running is simulated

Exercise

How does your own module share its functions?