-
Hajipur, Bihar, 844101
Hajipur, Bihar, 844101
JS Basics
JS Variables & Operators
JS Data Types & Conversion
JS Numbers & Math
JS Strings
JS Dates
JS Arrays
JS Control Flow
JS Loops & Iteration
JS Functions
JS Functions
Function Definitions
Function Parameters
Function Invocation
Function Call
Function Apply
Function Bind
Function Closures
JS Arrow Function
JS Objects
JS Objects
JS Object Properties
JS Object Methods
JS Object Display
JS Object Constructors
Object Definitions
Object Get / Set
Object Prototypes
Object Protection
JS Classes & Modules
JS Async Programming
JS Advanced
JS Destructuring
JS Bitwise
JS RegExp
JS Precedence
JS Errors
JS Scope
JS Hoisting
JS Strict Mode
JS this Keyword
JS HTML DOM
DOM Intro
DOM Methods
DOM Document
DOM Elements
DOM HTML
DOM Forms
DOM CSS
DOM Animations
DOM Events
DOM Event Listener
DOM Navigation
DOM Nodes
DOM Collections
DOM Node Lists
JS BOM (Browser Object Model)
JS Web APIs
Web API Intro
Web Validation API
Web History API
Web Storage API
Web Worker API
Web Fetch API
Web Geolocation API
JS AJAX
AJAX Intro
AJAX XMLHttp
AJAX Request
AJAX Response
AJAX XML File
AJAX PHP
AJAX ASP
AJAX Database
AJAX Applications
AJAX Examples
JS JSON
JSON Intro
JSON Syntax
JSON vs XML
JSON Data Types
JSON Parse
JSON Stringify
JSON Objects
JSON Arrays
JSON Server
JSON PHP
JSON HTML
JSON JSONP
JS Graphics & Charts
JavaScript modules provide a way to organize and structure code by splitting it into reusable, self-contained files. Modules allow developers to import and export functionality such as variables, functions, classes, and objects across different files. This approach improves code maintainability, promotes reusability, and makes large applications easier to manage. With the introduction of ES6, JavaScript natively supports modules using export and import statements.
In this tutorial, you will learn about JavaScript modules, how to create and use them, practical examples, common mistakes, best practices, and real-world applications.
Modules are important because they allow you to:
Break code into smaller, manageable files
Reuse code across multiple projects or files
Encapsulate functionality to prevent global scope pollution
Improve code readability and maintainability
Facilitate collaborative development in larger teams
Without modules, developers would need to include all code in a single file or rely on global variables, which can quickly become difficult to maintain and debug.
A module is simply a JavaScript file that exports variables, functions, or classes so they can be used in other files.
// student.js
export const name = "Aarushi";
export const age = 20;
export function greet() {
console.log("Hello, my name is " + name);
}
In this example, the constants name and age, along with the function greet, are exported from the file student.js.
You can export multiple items individually or together using named exports:
// utils.js
export const PI = 3.14159;
export function square(x) {
return x * x;
}
export function cube(x) {
return x * x * x;
}
To use exported items from another file, you use the import statement.
// main.js
import { name, greet } from "./student.js";
console.log(name); // Aarushi
greet(); // Hello, my name is Aarushi
Named imports must match the exported names exactly.
You can import all exports from a module as a single object:
// main.js
import * as Student from "./student.js";
console.log(Student.name); // Aarushi
Student.greet(); // Hello, my name is Aarushi
Modules can have a default export, which allows importing without using curly braces.
// course.js
export default class Course {
constructor(name) {
this.name = name;
}
details() {
console.log("Course: " + this.name);
}
}
// main.js
import Course from "./course.js";
const jsCourse = new Course("JavaScript");
jsCourse.details(); // Course: JavaScript
A module can have only one default export, but multiple named exports.
Dynamic imports allow you to load modules on demand, which can improve performance in large applications.
// main.js
async function loadCourseModule() {
const module = await import("./course.js");
const Course = module.default;
const jsCourse = new Course("React");
jsCourse.details();
}
loadCourseModule();
Dynamic imports return a promise and are useful for lazy loading or conditional module loading.
Forgetting to use relative paths when importing modules
Using curly braces with default exports incorrectly
Importing modules before they are properly exported
Mixing CommonJS (require) and ES6 modules (import/export)
Ignoring browser support and not using a bundler for older environments
Keep modules focused on a single responsibility
Use named exports for utility functions and constants
Use default exports for main functionality in a module
Organize modules logically in folders based on functionality
Use dynamic imports for performance optimization in large applications
Organizing utility functions, classes, and components in frontend frameworks like React or Vue
Creating reusable libraries for multiple projects
Structuring backend code in Node.js applications
Lazy loading modules in web applications to reduce initial load time
Encapsulating configuration and environment variables in separate files
// mathUtils.js
export function add(a, b) {
return a + b;
}
export function subtract(a, b) {
return a - b;
}
// main.js
import { add, subtract } from "./mathUtils.js";
console.log(add(5, 3)); // 8
console.log(subtract(5, 3)); // 2
// user.js
export default class User {
constructor(name) {
this.name = name;
}
greet() {
console.log("Hello, " + this.name);
}
}
// main.js
import User from "./user.js";
const user = new User("Priya");
user.greet(); // Hello, Priya
// main.js
async function loadModule() {
const module = await import("./mathUtils.js");
console.log(module.add(10, 5)); // 15
}
loadModule();
// product.js
export const TAX_RATE = 0.1;
export default class Product {
constructor(name, price) {
this.name = name;
this.price = price;
}
totalPrice() {
return this.price + this.price * TAX_RATE;
}
}
// main.js
import Product, { TAX_RATE } from "./product.js";
const phone = new Product("Phone", 500);
console.log(phone.totalPrice()); // 550
console.log(TAX_RATE); // 0.1
JavaScript modules enable developers to structure code into reusable, self-contained files. With export and import, you can share variables, functions, classes, and objects across files while maintaining modularity and preventing global scope pollution. Using default exports, named exports, and dynamic imports, developers can write scalable, maintainable, and performance-optimized applications. Following best practices ensures clean code organization, efficient code reuse, and easier debugging.
Basic Named Export and Import
Create a module mathUtils.js that exports a function add(a, b) and a constant pi. Import them in another file and log their values.
Default Export
Create a module calculator.js with a default exported class Calculator that has an add() method. Import it in another file and create an instance to use the method.
Combining Named and Default Imports
Export a default class Calculator and a named function multiply from the same module. Import both in another file and use them.
Renaming Imports
Export a function subtract from a module and import it as minus in another file. Call the function to verify it works.
Dynamic Import
Use import() to dynamically load a module mathUtils.js and call an exported function add() asynchronously.
Module Scope
Create a variable in a module that is not exported, and another that is exported. Try accessing both from another file and observe which is accessible.
Re-exporting Modules
Create two modules mathUtils.js and calculator.js, then create a third module utilities.js that re-exports everything. Import everything from utilities.js in another file.
Multiple Named Exports
Export multiple functions (add, multiply, divide) from a single module. Import them individually and log their outputs.
Default Export with Renaming
Export a default class Person and import it with a different name in another file. Instantiate and use the class.
Organizing Modules
Create a folder structure with separate modules for math and string utilities. Import functions from both modules in a main file and use them together.
JS Basics
JS Variables & Operators
JS Data Types & Conversion
JS Numbers & Math
JS Strings
JS Dates
JS Arrays
JS Control Flow
JS Loops & Iteration
JS Functions
JS Functions
Function Definitions
Function Parameters
Function Invocation
Function Call
Function Apply
Function Bind
Function Closures
JS Arrow Function
JS Objects
JS Objects
JS Object Properties
JS Object Methods
JS Object Display
JS Object Constructors
Object Definitions
Object Get / Set
Object Prototypes
Object Protection
JS Classes & Modules
JS Async Programming
JS Advanced
JS Destructuring
JS Bitwise
JS RegExp
JS Precedence
JS Errors
JS Scope
JS Hoisting
JS Strict Mode
JS this Keyword
JS HTML DOM
DOM Intro
DOM Methods
DOM Document
DOM Elements
DOM HTML
DOM Forms
DOM CSS
DOM Animations
DOM Events
DOM Event Listener
DOM Navigation
DOM Nodes
DOM Collections
DOM Node Lists
JS BOM (Browser Object Model)
JS Web APIs
Web API Intro
Web Validation API
Web History API
Web Storage API
Web Worker API
Web Fetch API
Web Geolocation API
JS AJAX
AJAX Intro
AJAX XMLHttp
AJAX Request
AJAX Response
AJAX XML File
AJAX PHP
AJAX ASP
AJAX Database
AJAX Applications
AJAX Examples
JS JSON
JSON Intro
JSON Syntax
JSON vs XML
JSON Data Types
JSON Parse
JSON Stringify
JSON Objects
JSON Arrays
JSON Server
JSON PHP
JSON HTML
JSON JSONP
JS Graphics & Charts
