Modern JS & AsyncExtra· 30 min read

Modules: import & export

Split your code across files and share functions between them — how every real project is organised.

What you will learn

  • Export values from a file
  • Import them into another
  • Understand why modules matter

Share code between files

Real apps split code into many files (modules). You export from one file and import into another.

Picture two files. The first one, math.js, exports the things it wants to share with other files.

Export from math.js
// math.js
export function add(a, b) { return a + b; }
export const PI = 3.14159;

The word export in front of add and PI marks them as "available to other files". Anything without export stays private to math.js.

The second file, app.js, imports those shared things and uses them.

Import into app.js
// app.js
import { add, PI } from './math.js';
console.log(add(2, 3));   // 5
console.log(PI);

import { add, PI } from './math.js' pulls those two names in by matching their names exactly. After that line, add and PI work here as if they were written in this file — so add(2, 3) returns 5.

Note: Output (in the console): 5 3.14159

  1. In math.js, put export in front of each value you want to share.
  2. In app.js, import { ... } from './math.js' to bring those names in.
  3. Use the imported names normally — they behave just like local code.

Note: To use modules in the browser, add type="module" to your script tag: <script type="module" src="app.js"></script>. React and Node use this import/export system everywhere.

Tip: There is also a default export (export default) for a file’s main thing, imported without braces. You will see both styles constantly in React projects.

Q. Which keyword brings a function from another file into this one?

Answer: import brings in values that another file exports. (Node’s older style uses require, but modern JS/React use import/export.)

✍️ Practice

  1. Create a utils.js that exports two functions and import them into another file.
  2. Try a default export and import it without braces.

🏠 Homework

  1. Split a small program into two files using import/export.
Want to learn this with a mentor?

CodingClave runs guided, project-based training (28-day, 45-day & 6-month batches).

Explore Training →