Share Code with Modules

Share Code with Modules

A module exposes selected declarations with export and imports declarations from another module. It has its own scope. The complete single-file calculation below becomes a genuine two-file module in the additional project section.

Before this topic, review Create Objects with Classes if its terms are unfamiliar.

What you’ll learn

  • Explain share code with modules through the school example.
  • Trace the shown operations and distinguish their result from displayed output.
  • Make the practice change and explain its consequence: The rule behaves identically when imported; it receives 40 and returns false.

Work through the school example

This is JavaScript using language features and the host console. Read the initial values, then follow each operation to its displayed result. A declaration names a value, a function call performs an operation, and console.log displays its arguments.

JavaScript · school.js · complete example

function passed(mark) {
  return mark >= 50;
}
console.log(passed(72));

Expected output

true
Run in JavaScript compiler →

Introduction to JavaScript Modules

Modules help in breaking a JavaScript codebase into reusable and manageable pieces. Before ES6, developers used patterns like IIFEs or libraries like RequireJS to emulate modularity. ES6 introduced native support for modules through export and import.

Why Use Modules?

  • Helps organize code into separate files.
  • Encourages reusability and separation of concerns.
  • Improves maintainability and scalability of applications.

Types of Exports

  • Named Export - Export multiple values by name.
  • Default Export - Export a single value as the default.

Using Named Exports

Let's create a file mathUtils.js and export multiple functions:

// mathUtils.js
export function add(a, b) {
  return a + b;
}

export function subtract(a, b) {
  return a - b;
}

Now, import them into another file:

// app.js
import { add, subtract } from './mathUtils.js';

console.log(add(10, 5));
console.log(subtract(10, 5));
15
5

Using Default Exports

Suppose a module has only one primary export, you can use export default:

// logger.js
export default function log(message) {
  console.log('Log:', message);
}

Importing a default export does not require curly braces:

// app.js
import log from './logger.js';

log('Modules are awesome!');
Log: Modules are awesome!

Can You Combine Named and Default Exports?

Yes, a file can contain both:

// helpers.js
export default function greet(name) {
  return `Hello, ${name}`;
}

export const PI = 3.14;
// app.js
import greet, { PI } from './helpers.js';

console.log(greet('JavaScript'));
console.log(PI);
Hello, JavaScript
3.14

Running JavaScript Modules

If using in Node.js, ensure the file extension is .mjs or add "type": "module" to your package.json.

node app.mjs

If using in browser, use type="module" in your script tag (for completeness, but not needed here).

Common Questions

Can I rename an imported function?

Yes, using as keyword:

import { add as sum } from './mathUtils.js';
console.log(sum(2, 3));
5

Can I import everything?

Yes, using * as syntax:

import * as math from './mathUtils.js';

console.log(math.add(1, 2));
console.log(math.subtract(5, 3));
3
2

Summary

  • export lets you share functions, variables, or objects.
  • import allows you to bring those into another file.
  • Use default export when the module has a single main value.
  • Use named exports to share multiple utilities.

Mastering modules will help you write cleaner, modular, and maintainable code for large applications.

Recognize the important boundary

Serve browser modules over HTTP and use type=module. Imports use resolvable URLs; export syntax alone does not create a server or install packages.

Try a small variation

JavaScript · original source for practice

function passed(mark) {
  return mark >= 50;
}
console.log(passed(72));

Your task: Replace passed(72) with passed(40). Predict the result before running the edited program.

The source is repeated here. If the edit targets the HTML rather than the script, use the markup repeated below; the worked answer also repeats the changed markup.

Worked answer and reasoning

The rule behaves identically when imported; it receives 40 and returns false.

JavaScript · complete worked variation

function passed(mark) {
  return mark >= 50;
}
console.log(passed(40));

Expected output

false
Run in JavaScript compiler →

Predict the original program

JavaScript · original program for this question

function passed(mark) {
  return mark >= 50;
}
console.log(passed(72));
What does the original JavaScript program display, in order?
Choose one answer. You can try again.

Answer and explanation

true

A module exposes selected declarations with export and imports declarations from another module. It has its own scope. The complete single-file calculation below becomes a genuine two-file module in the additional project section. Serve browser modules over HTTP and use type=module. Imports use resolvable URLs; export syntax alone does not create a server or install packages.

Run actual ES modules

These are two separate JavaScript files. Serve their directory over HTTP and load main.js with <script type="module" src="main.js"></script>. The browser resolves the relative module URL from main.js.

grade.js

export function passed(mark) { return mark >= 50; }

main.js

import {passed} from "./grade.js";
console.log(passed(72));

Expected output: true. Changing the argument to 40 prints false. Imports provide a live binding to an exported name; they do not copy the source into your function body.

Keep the useful idea

A module exposes selected declarations with export and imports declarations from another module. It has its own scope. The complete single-file calculation below becomes a genuine two-file module in the additional project section.

Check your variation against this explanation: The rule behaves identically when imported; it receives 40 and returns false.

Use the JavaScript array reference library for individual array operations and boundary tests to check a rule independently.

Reaching the recap and completing the quizzes are separate milestones.

    Next lesson: Read an Optional Property Safely →