theory.js

Modules & Code Organisation

Import & Export

JavaScript modules allow you to split code into separate files and reuse them.

  • `export` lets you expose functions, variables, or classes.
  • `import` allows other files to access exported values.
  • Named exports: `export { myFunction }` / `import { myFunction } from './module'`
  • Default exports: `export default myFunction` / `import myFunction from './module'`
// module.js (Named Export)
export const greet = (name) => `Hello, ${name}!`;

// module.js (Default Export)
export default function sayHi() {
  return "Hi there!";
}

// main.js
import { greet } from './module.js'; // Named import
import sayHi from './module.js'; // Default import

console.log(greet("Jake")); // "Hello, Jake!"
console.log(sayHi()); // "Hi there!"