modules

JavaScript Modules

JavaScript Modules

Modules allow you to split JavaScript code into smaller, reusable pieces. This makes it easier to manage and maintain code.

Importing and Exporting Modules

To use a module, export its functions or variables, and import them into other files:

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

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

Activity

Try It Yourself!

Create two files: one that exports a function and another that imports and uses that function.

Quiz

Quick Quiz

  1. What are JavaScript modules used for?
  2. How do you import a module?
  3. What is the difference between export and import?

Answers: Organize code into smaller parts; use import; export makes the code reusable, import uses it.