# DAY 13 - Understanding JavaScript Modules

Screenshot:-

![](https://cdn.hashnode.com/res/hashnode/image/upload/v1721924584183/e196780b-0334-4252-80ff-d4132dcfb9a7.png align="center")

  
JavaScript modules are a way to structure and organize code, making it more manageable, reusable, and maintainable. This guide will take you through creating, exporting, and importing modules, as well as using third-party modules and module bundling. By the end, you'll have a solid grasp of how to work with modules in JavaScript.

### 1\. Creating and Exporting Modules

Modules allow you to encapsulate code and export it for use in other scripts.

**Task 1: Creating a Module to Add Two Numbers**

First, create a file named `math.js` with the following content:

```javascript
// math.js
function add(a, b) {
  return a + b;
}

module.exports = add;
```

Next, create another file `app.js` to import and use the `add` function:

```javascript
// app.js
const add = require('./math');

const sum = add(3, 5);
console.log(`Sum: ${sum}`);
```

**Task 2: Creating a Module to Represent a Person**

Create a file named `person.js` with the following content:

```javascript
// person.js
const person = {
  name: 'John Doe',
  age: 30,
  greet() {
    console.log(`Hello, my name is ${this.name}`);
  },
};

module.exports = person;
```

Then, create another file `app.js` to import and use the `person` object:

```javascript
// app.js
const person = require('./person');

console.log(person.name);
person.greet();
```

### 2\. Named and Default Exports

Named exports allow you to export multiple values from a module, while default exports allow you to export a single value.

**Task 3: Using Named Exports**

Create a file named `utils.js` with the following content:

```javascript
// utils.js
export function add(a, b) {
  return a + b;
}

export function subtract(a, b) {
  return a - b;
}
```

Then, create another file `app.js` to import and use these functions:

```javascript
// app.js
import { add, subtract } from './utils';

console.log(`Add: ${add(3, 5)}`);
console.log(`Subtract: ${subtract(9, 4)}`);
```

**Task 4: Using Default Export**

Create a file named `defaultExport.js` with the following content:

```javascript
// defaultExport.js
export default function greet(name) {
  console.log(`Hello, ${name}`);
}
```

Then, create another file `app.js` to import and use this function:

```javascript
// app.js
import greet from './defaultExport';

greet('Alice');
```

### 3\. Importing Entire Modules

Sometimes, it's useful to import an entire module as an object.

**Task 5: Importing Entire Module as an Object**

Create a file named `constants.js` with the following content:

```javascript
// constants.js
export const PI = 3.14;
export const E = 2.71;

export function circleArea(radius) {
  return PI * radius * radius;
}

export function naturalLogarithm(x) {
  return Math.log(x) / Math.log(E);
}
```

Then, create another file `app.js` to import and use the entire module:

```javascript
// app.js
import * as constants from './constants';

console.log(`PI: ${constants.PI}`);
console.log(`Area: ${constants.circleArea(5)}`);
console.log(`Log: ${constants.naturalLogarithm(10)}`);
```

### 4\. Using Third-Party Modules

Third-party modules can be installed via npm and used in your projects.

**Task 6: Using lodash**

First, install lodash using npm:

```javascript
npm install lodash
```

Create a file `app.js` to import and use lodash:

```javascript
// app.js
import _ from 'lodash';

const array = [1, 2, 3, 4, 5];
console.log(_.shuffle(array));
```

**Task 7: Using axios**

First, install axios using npm:

```javascript
npm install axios
```

Create a file `app.js` to import and use axios:

```javascript
// app.js
import axios from 'axios';

axios.get('https://jsonplaceholder.typicode.com/todos/1')
  .then(response => {
    console.log(response.data);
  })
  .catch(error => {
    console.error('Error:', error);
  });
```

### 5\. Module Bundling (Optional)

Module bundlers like Webpack or Parcel allow you to bundle multiple JavaScript files into a single file.

**Task 8: Using Webpack**

First, install Webpack and its CLI:

```javascript
npm install --save-dev webpack webpack-cli
```

Create a `webpack.config.js` file:

```javascript
// webpack.config.js
const path = require('path');

module.exports = {
  entry: './src/index.js',
  output: {
    filename: 'bundle.js',
    path: path.resolve(__dirname, 'dist'),
  },
};
```

Create a `src/index.js` file:

```javascript
// src/index.js
import { add, subtract } from './utils';

console.log(`Add: ${add(3, 5)}`);
console.log(`Subtract: ${subtract(9, 4)}`);
```

Then, run Webpack:

```javascript
npx webpack --config webpack.config.js
```

### Conclusion and Additional Resources

By mastering modules, you can write cleaner, more modular JavaScript code. Modules help organize your code, making it easier to maintain and reuse. For further reading, check out these resources:

* [MDN Web Docs: Import](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/import)
    
* [MDN Web Docs: Export](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/export)
    
* Node.js Modules
    
* Webpack Documentation
