w1coding.comAll tutorials

JavaScript Modules

JavaScript lessons
  1. Environment Setup
  2. Introduction
  3. Enviroment
  4. Basics
  5. Variables
  6. Operators
  7. Condition
  8. Functions
  9. Arrays
  10. Bjects
  11. DOM
  12. Objects
  13. Colors
  14. DOM
  15. Events
  16. Validation
  17. JSON
  18. Error
  19. Callbacks
  20. Promises
  21. Fetch
  22. Local
  23. Modules
  24. Animation
  25. Classes
  26. Iframes
  27. Responsive

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.