In JavaScript, a module is essentially an individual assortment of functions, objects, or values that can be utilized throughout an application. With the use of modules in JavaScript, you can easily divide your code into different parts (each with a specific job). This makes the code easier to understand, debug and maintain.
A JavaScript program can consist of several modules which depend on each other. This is achieved via the `export` and `import` statements.
EXPORT
The `export` statement is used when we want to make certain parts of a module available to be imported into another module. Here is a simple example:
```
// myModule.js
export const pi = 3.14159;
export function sum(x, y) {
return x + y;
}
```
In this example, we’re declaring `pi` as a named export and `sum` as a function.
IMPORT
On the other side, the `import` statement allows you to bring in exports from another module into the current module. Here is how you would import the above exported module:
```
// app.js
import { pi, sum } from ‘./myModule.js’;
console.log(pi); // 3.14159
console.log(sum(1, 2)); // 3
```
In `app.js`, we are importing the named exports `pi` and `sum` from `myModule.js.` We can now use these in `app.js`.
It is important to note that the syntax ‘./myModule.js’ refers to a local file in the same directory as our `app.js` file. Your correct file path may be different.
ALTERNATIVE SYNTAX
There is an alternative syntax for exporting and importing everything from a module.
```
// myModule.js
const pi = 3.14159;
function sum(x, y) {
return x + y;
}
export default { pi, sum };
```
Each module can have one default export. In this case, we’re exporting an object with `pi` and `sum` as properties.
```
// app.js
import module from ‘./myModule.js’;
console.log(module.pi); // 3.14159
console.log(module.sum(1, 2)); // 3
```
In `app.js`, we are importing the default export from `myModule.js`. We now access `pi` and `sum` as properties of this module.
It’s important to note also that ES6 module support might vary from one JavaScript environment to another so it might be necessary to use a module bundler like webpack or a transpiler like Babel in certain environments.