Assignments Of Day 21: Module System in JavaScript
Assignment
1: Working with Named Exports and Imports
Problem
Statement:
Create a JavaScript module that exports
two functions: multiply and divide. Then, create a separate file where you
import these functions and use them to perform multiplication and division
operations. Display the results in the console.
Step-by-Step
Solution:
1. Create
the Module with Named Exports
In this step, we will create a
file named math.js where we will define the two functions, multiply and divide,
and export them using named exports.
javascript
Copy code
//
math.js
//
Function to multiply two numbers
export
const multiply = (a, b) => {
return a * b;
};
//
Function to divide two numbers
export
const divide = (a, b) => {
if (b === 0) {
return "Cannot divide by zero";
}
return a / b;
};
Explanation:
o
In math.js, we define two functions: multiply and
divide.
o
Both functions are exported using the export
keyword, which makes them accessible from other files.
2. Create
the Main File to Import and Use the Functions
Now, we will create a file called
app.js where we will import the multiply and divide functions from the math.js
module and use them to perform calculations.
javascript
Copy code
// app.js
//
Importing multiply and divide functions from math.js
import {
multiply, divide } from './math.js';
// Using
the imported functions
console.log("Multiplication
of 5 and 3: " + multiply(5, 3)); // Output: 15
console.log("Division
of 6 by 2: " + divide(6, 2)); // Output: 3
console.log("Division
of 5 by 0: " + divide(5, 0)); // Output: Cannot divide by zero
Explanation:
o
In app.js, we import multiply and divide using the named
import syntax { multiply, divide }.
o
We call the functions and log the results to the
console.
Output:
plaintext
Copy code
Multiplication
of 5 and 3: 15
Division
of 6 by 2: 3
Division
of 5 by 0: Cannot divide by zero
Assignment
2: Using Default Export
Problem
Statement:
Create a module greet.js that
exports a single function greetUser as a default export. Then, create a file
main.js where you import and call this function to greet a user.
Step-by-Step
Solution:
1. Create
the Module with a Default Export
In this step, we will create a
module named greet.js where we will define the greetUser function and export it
as the default export.
javascript
Copy code
//
greet.js
//
Default export of the greetUser function
const
greetUser = (name) => {
return `Hello, ${name}! Welcome to JavaScript
Modules.`;
};
export
default greetUser;
Explanation:
o
greetUser is a simple function that takes a user's
name as a parameter and returns a greeting string.
o
We export greetUser as the default export using export
default.
2. Create
the Main File to Import and Use the Default Export
Now, we create the main.js file
where we will import the greetUser function and call it with a user's name.
javascript
Copy code
//
main.js
//
Importing the default export from greet.js
import
greetUser from './greet.js';
//
Calling the imported function
console.log(greetUser('Alice'));
// Output: Hello, Alice! Welcome to JavaScript Modules.
Explanation:
o
We import greetUser using the default import syntax
import greetUser from './greet.js';.
o
We call the greetUser function with 'Alice' as the
argument and log the result.
Output:
plaintext
Copy code
Hello,
Alice! Welcome to JavaScript Modules.
Assignment
3: Combining Default and Named Exports
Problem
Statement:
Create a module operations.js
that exports one default function called calculate and two named exports add
and subtract. Then, create a main file app.js to import and use all three
functions.
Step-by-Step
Solution:
1. Create
the Module with Default and Named Exports
First, create the module
operations.js where we define three functions: one for adding, one for
subtracting, and one for calculating both operations together.
javascript
Copy code
//
operations.js
// Named
export for add function
export
const add = (a, b) => {
return a + b;
};
// Named
export for subtract function
export
const subtract = (a, b) => {
return a - b;
};
//
Default export for calculate function
const
calculate = (a, b) => {
return `Addition: ${add(a, b)}, Subtraction:
${subtract(a, b)}`;
};
export
default calculate;
Explanation:
o
We export add and subtract as named exports, and
calculate as the default export.
o
The calculate function calls add and subtract and
returns a string showing both results.
2. Create
the Main File to Import and Use All Three Functions
Now, in the app.js file, we will
import and use both the named exports and the default export.
javascript
Copy code
// app.js
//
Importing the named exports and the default export from operations.js
import
calculate, { add, subtract } from './operations.js';
// Using
the functions
console.log(add(10,
5)); // Output: 15
console.log(subtract(10,
5)); // Output: 5
console.log(calculate(10,
5)); // Output: Addition: 15, Subtraction: 5
Explanation:
o
We use both named import { add, subtract } and
default import calculate from operations.js.
o
We call each function and display the results in
the console.
Output:
plaintext
Copy code
15
5
Addition:
15, Subtraction: 5
Assignment
4: Using Modules in the Browser
Problem
Statement:
Create two JavaScript files:
math.js and app.js. In math.js, export a function square using a named export.
In app.js, import the square function and use it to square a number. Create an
HTML file to link both JavaScript files and display the result.
Step-by-Step
Solution:
1. Create
the math.js Module
javascript
Copy code
//
math.js
// Named
export of square function
export
const square = (n) => {
return n * n;
};
Explanation:
o
The square function takes a number n and returns
its square. It's exported using a named export.
2. Create
the app.js File
javascript
Copy code
// app.js
//
Importing the square function from math.js
import {
square } from './math.js';
// Using
the square function and displaying the result in the console
console.log(square(5));
// Output: 25
Explanation:
o
The square function is imported using the named
import syntax and used to square the number 5.
3. Create
the HTML File to Include the JavaScript Modules
html
Copy code
<!--
index.html -->
<!DOCTYPE
html>
<html
lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport"
content="width=device-width, initial-scale=1.0">
<title>JavaScript Modules
Example</title>
</head>
<body>
<script type="module"
src="app.js"></script>
</body>
</html>
Explanation:
o
In the HTML file, we use the
type="module" attribute in the <script> tag to tell the browser
to treat the script as a module.
o
We link to the app.js file, which will
automatically import math.js.
Output
(in the browser console):
plaintext
Copy code
25
Conclusion
These assignments aim to help you
understand the fundamentals of JavaScript modules, including how to use both
named and default exports, as well as how to structure your code in modular
formats. Each assignment provides hands-on experience to reinforce the
concepts, making it easier for students to organize their code efficiently in
real-world projects.
4o mini
You said:
more
ChatGPT
said:
ChatGPT
Here are additional assignments
with step-by-step solutions, covering more scenarios involving JavaScript
modules.
Assignment
5: Using Multiple Named Exports
Problem
Statement:
Create a module shapes.js that
exports multiple functions using named exports. The functions will calculate
the area of a rectangle, circle, and triangle. Then, in a separate app.js file,
import all the functions and use them to calculate the area of different
shapes.
Step-by-Step
Solution:
1. Create
the shapes.js Module
In this module, we will define
functions to calculate the area of a rectangle, circle, and triangle, and
export them using named exports.
javascript
Copy code
//
shapes.js
//
Function to calculate the area of a rectangle
export
const rectangleArea = (length, width) => {
return length * width;
};
//
Function to calculate the area of a circle
export
const circleArea = (radius) => {
return Math.PI * radius * radius;
};
//
Function to calculate the area of a triangle
export
const triangleArea = (base, height) => {
return 0.5 * base * height;
};
Explanation:
o
rectangleArea, circleArea, and triangleArea are
functions that calculate areas for different shapes.
o
Each function is exported using named exports,
making them available for import in other files.
2. Create
the app.js File to Import and Use the Functions
Now, in the app.js file, we will
import the functions from shapes.js and use them to calculate areas.
javascript
Copy code
// app.js
//
Importing all functions from shapes.js
import {
rectangleArea, circleArea, triangleArea } from './shapes.js';
//
Calculate and display the areas
console.log("Rectangle
Area (5 x 10): " + rectangleArea(5, 10)); // Output: 50
console.log("Circle
Area (radius = 7): " + circleArea(7)); // Output: 153.93804002589985
console.log("Triangle
Area (base = 5, height = 8): " + triangleArea(5, 8)); // Output: 20
Explanation:
o
We import the functions rectangleArea, circleArea,
and triangleArea using the named import syntax.
o
We call each function with appropriate parameters
to calculate the area for each shape and log the result.
Output:
plaintext
Copy code
Rectangle
Area (5 x 10): 50
Circle
Area (radius = 7): 153.93804002589985
Triangle
Area (base = 5, height = 8): 20
Assignment
6: Re-exporting Modules
Problem
Statement:
You have two modules moduleA.js
and moduleB.js. In moduleA.js, you define a function greet and a constant name.
In moduleB.js, you will re-export everything from moduleA.js and then import it
in app.js to display a greeting message.
Step-by-Step
Solution:
1. Create
the moduleA.js File
In this module, we will define a
function and a constant, which we will then export.
javascript
Copy code
//
moduleA.js
// Define
a function to greet
export
const greet = () => {
return "Hello from module A!";
};
// Define
a constant name
export
const name = "Alice";
Explanation:
o
greet is a function that returns a greeting
message.
o
name is a constant that holds a name.
2. Create
the moduleB.js File to Re-export moduleA.js
In this step, we create
moduleB.js where we will re-export everything from moduleA.js.
javascript
Copy code
//
moduleB.js
//
Re-export everything from moduleA.js
export *
from './moduleA.js';
Explanation:
o
The export * from './moduleA.js'; statement re-exports
all exports from moduleA.js, making them available in moduleB.js.
3. Create
the app.js File to Import from moduleB.js
Finally, in app.js, we will
import everything from moduleB.js and use the imported greet function and name
constant.
javascript
Copy code
// app.js
//
Importing everything from moduleB.js
import {
greet, name } from './moduleB.js';
//
Display the greeting and name
console.log(greet());
// Output: Hello from module A!
console.log("The
name is: " + name); // Output: The name is: Alice
Explanation:
o
We import greet and name from moduleB.js.
o
We call the greet function and log the value of
name.
Output:
plaintext
Copy code
Hello
from module A!
The name
is: Alice
Assignment
7: Dynamic Imports
Problem
Statement:
Create a module mathOperations.js
that contains several mathematical operations, including add, subtract, and
multiply. Use dynamic imports in app.js to import and use these functions when
required (e.g., only when a user clicks a button).
Step-by-Step
Solution:
1. Create
the mathOperations.js Module
In mathOperations.js, define the
basic arithmetic operations.
javascript
Copy code
//
mathOperations.js
//
Function to add two numbers
export
const add = (a, b) => {
return a + b;
};
//
Function to subtract two numbers
export
const subtract = (a, b) => {
return a - b;
};
//
Function to multiply two numbers
export
const multiply = (a, b) => {
return a * b;
};
Explanation:
o
add, subtract, and multiply are basic mathematical
functions that perform the corresponding operations.
2. Create
the app.js File to Use Dynamic Imports
In this step, we will create
app.js, where we will use dynamic imports to load the mathOperations.js
functions only when needed.
javascript
Copy code
// app.js
// Button
click event to load add operation dynamically
document.getElementById('addButton').addEventListener('click',
async () => {
const { add } = await
import('./mathOperations.js');
console.log(add(5, 3)); // Output: 8
});
// Button
click event to load subtract operation dynamically
document.getElementById('subtractButton').addEventListener('click',
async () => {
const { subtract } = await
import('./mathOperations.js');
console.log(subtract(10, 4)); // Output: 6
});
// Button
click event to load multiply operation dynamically
document.getElementById('multiplyButton').addEventListener('click',
async () => {
const { multiply } = await
import('./mathOperations.js');
console.log(multiply(2, 3)); // Output: 6
});
Explanation:
o
We use import() inside event listeners to dynamically
load the functions only when a button is clicked.
o
The await import('./mathOperations.js') syntax is
used to load the mathOperations.js module dynamically.
3. Create
the HTML File to Trigger the Events
Here is the HTML code to display
buttons that the user can click to trigger the dynamic import of the functions.
html
Copy code
<!--
index.html -->
<!DOCTYPE
html>
<html
lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport"
content="width=device-width, initial-scale=1.0">
<title>Dynamic Imports
Example</title>
</head>
<body>
<button
id="addButton">Add</button>
<button
id="subtractButton">Subtract</button>
<button
id="multiplyButton">Multiply</button>
<script type="module"
src="app.js"></script>
</body>
</html>
Explanation:
o
The buttons are linked to corresponding operations:
Add, Subtract, and Multiply.
o
The app.js file is loaded as a module, which
handles the dynamic imports.
Output
(after clicking the buttons):
plaintext
Copy code
8
6
6
Conclusion
These assignments provide a
deeper understanding of how to work with JavaScript modules in different ways,
including using multiple named exports, re-exporting modules, dynamic imports,
and more. They allow students to practice both basic and advanced concepts that
are essential for structuring JavaScript code in a modular way, which is
critical for building scalable and maintainable applications.
