JavaScript Modules Practice Questions with Solutions

Introductions

JavaScript modules allow you to split code into separate files and reuse functions, variables, classes, and objects where needed. Modules make larger projects easier to organize, maintain, and debug.

In this chapter, you will practice export, import, named exports, default exports, importing multiple values, renaming imports, exporting functions and classes, and using modules in a real-world example. JavaScript Modules practice questions with solutions help to understand the concepts.

Note: JavaScript modules normally run through a web server or development environment. If you open an HTML file directly with file://, module imports may be blocked by the browser.

Question 1: Export a Function from a Module

Problem

Create a JavaScript file that exports an add() function, then import and use it in another JavaScript file.

Solution

math.js

export function add(a, b) {
    return a + b;
}

app.js

import { add } from "./math.js";

console.log(add(10, 20));

index.html

<script type="module" src="app.js"></script>

Output

30

Step-by-step Explanation

The function is exported from math.js:

export function add(a, b) {
    return a + b;
}

The export keyword makes the function available to other modules.

Then app.js imports it:

import { add } from "./math.js";

The function can now be used:

add(10, 20);

The HTML file must load the JavaScript file as a module:

<script type="module" src="app.js"></script>

Question 2: Export Multiple Functions

Problem

Create a module containing add(), subtract(), and multiply() functions. Import all three functions into another file.

Solution

math.js

export function add(a, b) {
    return a + b;
}

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

export function multiply(a, b) {
    return a * b;
}

app.js

import {
    add,
    subtract,
    multiply
} from "./math.js";

console.log(add(10, 5));
console.log(subtract(10, 5));
console.log(multiply(10, 5));

Output

15
5
50

Step-by-step Explanation

You can export multiple values from the same module:

export function add() {}
export function subtract() {}
export function multiply() {}

Then import exactly the values you need:

import {
    add,
    subtract,
    multiply
} from "./math.js";

Named exports are imported using their exported names inside { }.


Question 3: Use a Default Export

Problem

Create a module that exports one default function called greet() and use it in another file.

Solution

greeting.js

export default function greet(name) {
    return "Hello, " + name;
}

app.js

import greet from "./greeting.js";

console.log(greet("Rahul"));

Output

Hello, Rahul

Step-by-step Explanation

A default export is created using:

export default

Example:

export default function greet(name) {
    return "Hello, " + name;
}

When importing a default export, curly braces are not required:

import greet from "./greeting.js";

You can also choose a different local name:

import sayHello from "./greeting.js";

The imported function still refers to the same default export.


Question 4: Import a Default and Named Export Together

Problem

Create a module with one default export and two named exports. Import all of them into another file.

Solution

user.js

export default function greetUser(name) {
    return "Welcome, " + name;
}

export const role = "Student";

export function getCourse() {
    return "JavaScript";
}

app.js

import greetUser, {
    role,
    getCourse
} from "./user.js";

console.log(greetUser("Aman"));
console.log(role);
console.log(getCourse());

Output

Welcome, Aman
Student
JavaScript

Step-by-step Explanation

The module contains:

  • One default export
  • One named constant
  • One named function

The default export comes first in the import:

import greetUser, {
    role,
    getCourse
} from "./user.js";

Notice the difference:

import greetUser

is the default import.

{
    role,
    getCourse
}

contains the named imports.


Question 5: Rename an Imported Function

Problem

Export a function called calculateTotal and import it with a different name.

Solution

cart.js

export function calculateTotal(price, quantity) {
    return price * quantity;
}

app.js

import {
    calculateTotal as total
} from "./cart.js";

console.log(total(100, 3));

Output

300

Step-by-step Explanation

The original exported name is:

calculateTotal

The import renames it using as:

calculateTotal as total

Now the function can be called locally as:

total(100, 3);

This is useful when two different modules export values with the same name.


Question 6: Export a Constant and an Object

Problem

Create a module that exports a constant and a user object. Import both values into another file.

Solution

data.js

export const appName = "Student App";

export const user = {
    name: "Priya",
    age: 20,
    course: "JavaScript"
};

app.js

import {
    appName,
    user
} from "./data.js";

console.log(appName);
console.log(user.name);
console.log(user.course);

Output

Student App
Priya
JavaScript

Step-by-step Explanation

The module exports two values:

export const appName = "Student App";

and:

export const user = {
    name: "Priya",
    age: 20,
    course: "JavaScript"
};

They can then be imported using named imports:

import { appName, user } from "./data.js";

Question 7: Export a Class

Problem

Create a Student class in one file and export it. Import the class and create an object in another file.

Solution

Student.js

export class Student {

    constructor(name, course) {
        this.name = name;
        this.course = course;
    }

    showDetails() {
        console.log(
            this.name + " is learning " + this.course
        );
    }

}

app.js

import { Student } from "./Student.js";

const student = new Student(
    "Rahul",
    "JavaScript"
);

student.showDetails();

Output

Rahul is learning JavaScript

Step-by-step Explanation

The class is exported:

export class Student {

Then imported:

import { Student } from "./Student.js";

Now Student can be used normally:

const student = new Student(
    "Rahul",
    "JavaScript"
);

Modules are especially useful for separating classes into their own files.


Question 8: Import Everything from a Module

Problem

Create a module containing several functions and import all of them under a single name.

Solution

math.js

export function add(a, b) {
    return a + b;
}

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

export function multiply(a, b) {
    return a * b;
}

app.js

import * as math from "./math.js";

console.log(math.add(10, 5));
console.log(math.subtract(10, 5));
console.log(math.multiply(10, 5));

Output

15
5
50

Step-by-step Explanation

This syntax:

import * as math from "./math.js";

imports the module’s exported values under the namespace math.

You can then access the functions with:

math.add()
math.subtract()
math.multiply()

This can make it clear which module a function belongs to.


Question 9: Create Separate Modules for a Shopping Cart

Problem

Create a small shopping cart system using separate modules.

Solution

products.js

export const products = [
    {
        name: "Keyboard",
        price: 1000
    },
    {
        name: "Mouse",
        price: 500
    },
    {
        name: "Headphones",
        price: 1500
    }
];

cart.js

export function calculateTotal(products) {

    let total = 0;

    products.forEach(function(product) {
        total += product.price;
    });

    return total;
}

app.js

import { products } from "./products.js";
import { calculateTotal } from "./cart.js";

console.log("Products:", products);
console.log("Total:", calculateTotal(products));

Output

Products: [
    { name: "Keyboard", price: 1000 },
    { name: "Mouse", price: 500 },
    { name: "Headphones", price: 1500 }
]

Total: 3000

Step-by-step Explanation

The product data is kept in:

products.js

The calculation logic is kept in:

cart.js

The main application imports both:

import { products } from "./products.js";
import { calculateTotal } from "./cart.js";

This keeps different responsibilities separated.

A real project might have a structure such as:

project/
│
├── index.html
├── app.js
├── products.js
└── cart.js

This is one of the biggest benefits of modules: large code can be divided into smaller, manageable files.


Question 10: Build a Mini Modular JavaScript App

Problem

Create a small student application using separate modules for student data, calculations, and the main application.

Solution

student.js

export const student = {
    name: "Aman",
    marks: [80, 75, 90]
};

calculator.js

export function calculateAverage(marks) {

    let total = 0;

    marks.forEach(function(mark) {
        total += mark;
    });

    return total / marks.length;
}

app.js

import { student } from "./student.js";
import { calculateAverage } from "./calculator.js";

const average = calculateAverage(student.marks);

console.log("Student:", student.name);
console.log("Average:", average);

index.html

<script type="module" src="app.js"></script>

Output

Student: Aman
Average: 81.66666666666667

Step-by-step Explanation

The project contains three JavaScript files.

1. student.js

Stores the student’s information:

export const student = {
    name: "Aman",
    marks: [80, 75, 90]
};

2. calculator.js

Contains the calculation logic:

export function calculateAverage(marks) {
    // calculation
}

3. app.js

Connects everything together:

import { student } from "./student.js";
import { calculateAverage } from "./calculator.js";

The application then calculates the average:

const average = calculateAverage(student.marks);

This is a simple example of separation of concerns.

Instead of putting everything into one large JavaScript file, each file has a specific responsibility.

Key Takeaways

  • JavaScript modules allow code to be divided into separate files.
  • export makes values available to other modules.
  • import brings exported values into another module.
  • Named exports use curly braces during import.
  • Default exports do not require curly braces.
  • A module can have multiple named exports.
  • A module can have one default export.
  • as can rename an imported value.
  • import * as name imports multiple exports under a namespace.
  • Functions, variables, objects, and classes can all be exported.
  • Use type="module" when loading a JavaScript module from HTML.
  • Module paths commonly use relative paths such as ./math.js.
  • Modules help keep large applications organized.
  • Modules encourage separation of responsibilities.
  • JavaScript modules are commonly used in modern frontend applications.
  • Browser modules follow JavaScript module rules such as module scope and CORS restrictions.

FAQs

1. What is a JavaScript module?

A JavaScript module is a separate JavaScript file that can expose selected code for use by other JavaScript files.

For example:

export function add(a, b) {
    return a + b;
}

Another file can import it:

import { add } from "./math.js";

2. What is the difference between export and import?

export makes a value available outside its module.

export const name = "Rahul";

import brings that exported value into another module.

import { name } from "./user.js";

In simple terms:

export → send code out
import → bring code in

3. What is a named export?

A named export is an exported value that is imported using its exported name.

export function add(a, b) {
    return a + b;
}

Import it with:

import { add } from "./math.js";

4. What is a default export?

A default export is the primary default value of a module.

export default function greet() {
    console.log("Hello");
}

It can be imported without curly braces:

import greet from "./greeting.js";

The local name can be chosen by the importing file.

5. Can a JavaScript module have multiple named exports?

Yes.

export const name = "Aman";

export const age = 20;

export function greet() {
    console.log("Hello");
}

They can be imported together:

import {
    name,
    age,
    greet
} from "./data.js";

6. Why do we use type="module" in HTML?

When using browser JavaScript modules, the script should be loaded as a module:

<script type="module" src="app.js"></script>

This tells the browser to treat app.js as an ES module, allowing import and export syntax.

7. Why might JavaScript modules not work when I open an HTML file directly?

Browsers apply security rules to module requests. Opening a page directly with a file:// URL can cause module imports to fail.

For example, this setup:

index.html
app.js
math.js

should generally be tested through a local development server rather than simply double-clicking index.html.

Written by Shubhranshu Shekhar, who has trained 20000+ students in coding.

Scroll to Top