In JavaScript, modules are reusable pieces of code that can be imported and exported between files. They help in organizing code by breaking it into smaller, manageable parts, promoting reusability and maintainability.
JavaScript uses ES6 Modules (ECMAScript 2015), where we use the export
and import
keywords.
Let's create a file named math.js
that contains functions for addition and subtraction:
Now, in another file app.js
, we can import and use these functions:
A module can have a default export, which allows importing without curly braces {}
.
Would you like more advanced examples, like dynamic imports or CommonJS modules? 🚀