DEV Community

Cover image for JavaScript : Modules and ES6 Modules (English/Hindi)
Dharmik Dholu
Dharmik Dholu

Posted on

JavaScript : Modules and ES6 Modules (English/Hindi)

English

JavaScript modules are a way to organize and structure your code by splitting it into smaller, reusable pieces. ES6 (ECMAScript 2015) introduced a standardized module system known as ES6 modules, which provide a more efficient and organized way to manage dependencies in your JavaScript code.

Here's how you can create and use ES6 modules:

Creating a Module (math.js):

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

export function subtract(a, b) {
  return a - b;
}
Enter fullscreen mode Exit fullscreen mode

In this example, we have created a module named math.js that exports two functions, add and subtract, using the export keyword.

Using a Module (main.js):

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

const result1 = add(5, 3);
const result2 = subtract(10, 4);

console.log(result1); // 8
console.log(result2); // 6
Enter fullscreen mode Exit fullscreen mode

In the main.js file, we import the functions add and subtract from the math.js module using the import statement. This allows us to use these functions in our main.js file.

Hindi

JavaScript modules ek tarika hain apne code ko vyavasthit aur structure kiya jaane ka, jahan aap apna code chhote, punargunvanneeya tukdon mein baat karke likh sakte hain. ES6 (ECMAScript 2015) ne ek mukhya module pranali ko prastut kiya, jise ES6 modules ke roop mein jaana jaata hai, jo aapke JavaScript code mein dependencies (aavashyakataayein) ko prabandhit karne ka ek adhik upayukt aur vyavasthit tarike ka pradaan karte hain.

Neeche bataya gaya hai kis prakar se aap ES6 modules ko banate hain aur upayog karte hain:

Module Banane Ka Tariqa (math.js):

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

export function subtract(a, b) {
  return a - b;
}
Enter fullscreen mode Exit fullscreen mode

Is udaharan mein, hamne ek module math.js banaya hai jo export shabd ka upayog karke do functions, add aur subtract, ko bahar nikalta hai.

Module Ka Upayog Karne Ka Tariqa (main.js):

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

const result1 = add(5, 3);
const result2 = subtract(10, 4);

console.log(result1); // 8
console.log(result2); // 6
Enter fullscreen mode Exit fullscreen mode

main.js file mein, ham import statement ka upayog karke math.js module se functions add aur subtract ko import karte hain. Isse ham apne main.js file mein in functions ka upayog kar sakte hain.

Top comments (0)