Загрузка...

JavaScript Modules - Day - 24

🚀 Day-24: Modules (ESM) in JavaScript

JavaScript Modules allow developers to split code into multiple reusable files, making applications easier to maintain, scale, and organize.

ESM (ECMAScript Modules) is the modern module system introduced in ES6 (ES2015). It allows us to export code from one file and import it into another file.

Modules help avoid global scope pollution and improve code reusability.

🔹 Why Modules Are Needed

In large applications, writing all code in a single file becomes difficult to manage.

Problems without modules:

• Code becomes messy
• Hard to maintain large applications
• Global variable conflicts
• Difficult to reuse code

Modules solve these problems by separating code into independent files.

🔹 Exporting from a Module

The export keyword is used to expose variables, functions, or classes from a module.

Example:

// math.js

export const add = (a, b) ⇒ {
return a + b;
};

export const subtract = (a, b) ⇒ {
return a - b;
};

Here, the functions add and subtract are exported so they can be used in other files.

🔹 Importing a Module

The import keyword is used to use exported code from another module.

Example:

// app.js

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

console.log(add(5, 3));
console.log(subtract(10, 4));

Output:

8
6

Now the functions from math.js are available in app.js.

🔹 Default Export

JavaScript modules also support default export, which allows exporting a single main value from a file.

Example:

// greet.js

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

Importing default export:

import greet from "./greet.js";

greet();

🔹 Advantages of Modules

✔ Better code organization
✔ Reusable components
✔ Avoids global variable conflicts
✔ Easier debugging and maintenance
✔ Supports modern JavaScript applications

🔹 Interview Definition

JavaScript Modules (ESM) are a feature that allows developers to split code into reusable files and share functionality between them using export and import statements.

⭐ Simple Way to Remember

export ⇒ share code from a file
import ⇒ use code from another file

👍 Like & Subscribe SMART TECHIES HUB
for daily JavaScript interview questions 🚀

Видео JavaScript Modules - Day - 24 канала SMART TECHIES HUB
Яндекс.Метрика
Все заметки Новая заметка Страницу в заметки
Страницу в закладки Мои закладки
На информационно-развлекательном портале SALDA.WS применяются cookie-файлы. Нажимая кнопку Принять, вы подтверждаете свое согласие на их использование.
О CookiesНапомнить позжеПринять