Hackforge Academy

Category: javascript

JavaScript modules

Published on 22 Mar 2026

Explanation

JavaScript modules allow you to split code into separate files and reuse them across an application. Modules help organize code, improve maintainability, avoid global scope pollution. ES6 introduced a standard module system using export and import.

Code:

// math.js
export const pi = 3.14;
export function add(a, b) {
  return a + b;
}

// app.js
import { pi, add } from './math.js';

console.log(pi);
console.log(add(2, 3));

Explanation

Named export allows you to export multiple variables, functions, or classes from a module. Each exported item must be imported using the same name.

Code:

// utils.js
export const name = 'Praveen';
export function greet() {
  return 'Hello';
}

// main.js
import { name, greet } from './utils.js';

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

Explanation

Default export allows a module to export a single main value. When importing, you can give it any name.

Code:

// logger.js
export default function log(message) {
  console.log(message);
}

// app.js
import log from './logger.js';

log('Hello World');

Explanation

You can import all exports from a module using the '*' syntax and assign them to an object.

Code:

// math.js
export const a = 10;
export const b = 20;

// app.js
import * as math from './math.js';

console.log(math.a);
console.log(math.b);

Explanation

You can rename imports using the 'as' keyword while importing modules.

Code:

// math.js
export function add(x, y) {
  return x + y;
}

// app.js
import { add as sum } from './math.js';

console.log(sum(5, 3));

Explanation

Dynamic import allows modules to be loaded only when needed. It returns a Promise and is useful for code splitting and lazy loading.

Code:

import('./math.js').then(module => {
  console.log(module.add(2, 3));
});

πŸš€ Learn Spring Boot with real-world projects

πŸ’‘ Build REST APIs step by step

🧠 Improve backend development skills

🎯 Get career-ready practical training

Join Our Free WhatsApp Community

Direct access to niche-specific mentors and peers on WhatsApp.

🐍

Python Community

Discuss Django, FastAPI, AI integration, and automation scripts with 15k+ developers.

Join Python Community
βš›οΈ

React Community

Master Next.js, Framer Motion, and State Management. Share your latest UI components.

Join React Community
β˜•

Java Community

Deep dives into Spring Boot, Microservices architecture, and high-performance backend ops.

Join Java Community