Sample Video Frame

Created by Zed A. Shaw Updated 2024-02-17 04:54:36

31: Modules and import

Originally JavaScript had no concept of "modules" because it lived entirely in the browser. A systems language needs to have modules, so Node.JS added modules through the CommonJS system. This uses the require function to load modules, which you've been using this whole time.

In Exercise 13 you wrote a simple module named geometry.js:

const area = (r) => Math.PI * r ** 2;
const circumference = (r) => 2 * Math.PI * r;

module.exports = {
    area: area,
    circumference: circumference

This code exposed the area and circumference functions using the module.exports "magic" variable.

You then used require("./geometry") to access it:

const geometry = require('./geometry');

let area51 = geometry.area(2.8);
let circ2 = geometry.circumference(6);

console.log(`Area: ${area51}, Circumference: ${circ2}`);

This works as the default system in Node.JS, and during the course I stuck to the default to keep things simple. You now need to learn about the "module" version of...modules.

Previous Lesson Back to Module

Register for Learn JavaScript the Hard Way

Register today for the course and get the all currently available videos and lessons, plus all future modules for no extra charge.