0
0
Javascriptprogramming~5 mins

Why modules are used in Javascript

Choose your learning style9 modes available
Introduction

Modules help organize code by splitting it into smaller, reusable pieces. This makes programs easier to understand and maintain.

When your program grows too big and you want to keep code neat.
When you want to reuse the same code in different parts of your app.
When you want to share code with others or use code from libraries.
When you want to avoid naming conflicts by keeping variables and functions private.
When you want to load only the code you need, improving performance.
Syntax
Javascript
export function greet() {
  console.log('Hello!');
}

import { greet } from './greet.js';
greet();
Use export to share code from a module.
Use import to bring code from another module.
Examples
Export a function from one file and import it in another to use it.
Javascript
// greet.js
export function greet() {
  console.log('Hello!');
}

// main.js
import { greet } from './greet.js';
greet();
Export constants and functions, then import them where needed.
Javascript
// math.js
export const pi = 3.14;
export function area(radius) {
  return pi * radius * radius;
}

// app.js
import { pi, area } from './math.js';
console.log(area(2));
Sample Program

This program shows how to export a function from one file and import it in another to add two numbers.

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

// main.js
import { add } from './math.js';
console.log(add(5, 3));
OutputSuccess
Important Notes

Modules run in strict mode by default, which helps catch errors.

File paths in import statements usually need the file extension like .js.

Modules help avoid global variables that can cause bugs.

Summary

Modules split code into smaller, manageable parts.

They let you reuse and share code easily.

Modules keep code organized and prevent conflicts.