JavaScript modules
containing chunks of code for later re-use
// updated 2025-05-07 16:05
Modules in JavaScript allow for cleaner code and organization of concerns:
- namespace cleanliness
- variable names do not get reused and cause confusion
- functional focus
- does one thing and one thing well
- this specialization makes the code more portable and shareable
Creating (and exporting) a module
To create a module, we would create a variable:
const moduleToExport = {
property1: "hi",
property2: function() { return true },
property3: function() { return "hi" },
...
}
export default moduleToExport
Then, we would just use the keywords export default
before the variable name to allow re-use of this code.
Using (importing) a module
On the flip side, we would use a module with the import
keyword and following syntax:
import * as ImportedModule from './moduleToExport.js'
console.log(ImportedModule.property3)
// "hi"