JavaScript Modules

1. What are JavaScript Modules?

As your application grows, keeping all code in a single file becomes unmanageable. Modules allow you to break up your code into separate files. This makes it easier to maintain the code-base, reuse logic, and keep the global namespace clean.

ES6 Modules (also known as ECMAScript Modules or ESM) are the official standard format to package JavaScript code for reuse.

2. Named Exports

You can export multiple values (functions, variables, classes) from a module using named exports. You must use the exact same name when importing them.

In-line Export

// file: math.js
export const PI = 3.14159;

export function add(a, b) {
    return a + b;
}
        

Export All at Once

// file: user.js
const name = "Ragini";
const age = 25;

export { name, age };
        

3. Default Exports

You can have only one default export per file. This is useful for modules that export a single class or a main function. You can name it whatever you want when importing.

// file: message.js
const message = () => {
    const name = "Jesse";
    const age = 40;
    return name + ' is ' + age + ' years old.';
};

export default message;
        

4. Importing Modules

You import modules into a file using the import keyword.

Importing Named Exports

Named exports must be destructured using curly braces {}.

import { PI, add } from "./math.js";

console.log(PI);
console.log(add(5, 10));
        

Importing Default Exports

Default exports do not use curly braces.

import message from "./message.js";

console.log(message());
        

Importing Everything (Namespace)

You can import all exported values as an object.

import * as MathUtils from "./math.js";

console.log(MathUtils.PI);
console.log(MathUtils.add(2, 3));
        

5. Comparison Table: Module vs Non-Module

Feature Modules Non-Modules (Scripts)
Scope File Scoped (Variables are private by default) Global Scoped (Variables can pollute window)
Strict Mode Always enabled ("use strict") Optional
Loading Deferred by default (doesn't block HTML) Blocks HTML parsing unless defer is used
Execution Executed only once Executed every time included
Note: Modules only work via HTTP(s) protocol (like a live server). If you open an HTML file directly from your file system (file://), modules will be blocked by CORS policy.

Practice Questions

Test your understanding of JavaScript Modules.

Easy

Q1: Export a variable using named export.

  • Assume you have a constant variable named apiKey with the value "12345ABC".
  • Write the syntax to export it so it can be imported with the exact same name in another file.
Easy

Q2: Import a default export.

  • Assume there is a default function named calculateTax in a file called tax.js.
  • Write the syntax to import it into your current file.
Medium

Q3: Import all named exports as a single object.

  • Assume you have a file utils.js that exports multiple functions (add, subtract, multiply).
  • Write the code to import all of them as a single namespace object named mathOps.
Medium

Q4: Rename an imported function.

  • Assume a file api.js exports a function named fetchData.
  • Write the import statement to rename this function to getUserData to avoid naming conflicts.
Hard

Q5: Combine default and named exports.

  • Assume module.js exports a default function init and a named constant version.
  • Write the syntax to export them in module.js.
  • Write the syntax to import both the default export and the named export simultaneously in one line in main.js.

Answer

Code: