JavaScript Modules
JS
What are JavaScript Modules?
JavaScript modules are a way to split your code into separate files and pieces. Each file can export variables, functions, classes, etc. that can then be imported and used in other files.
Modules help in:
- Keeping code organized and easy to maintain
- Avoiding global namespace pollution
- Reusing code across different files or projects
Example: ES6 Modules
Exporting
Suppose you have a file called math.js:
Importing
In another file called app.js, you can use these exports:
multiply
is imported without curly braces because it was exported asdefault
.add
andPI
are imported using because they are named exports.
Why use modules?
- To keep code modular, meaning easier to understand and test.
- To avoid naming conflicts (everything is scoped to the module by default).
- To load only the parts you need