Monday, 24 February 2025

Import of modules using import and export

A JavaScript module is a reusable piece of code that can be exported from one file and imported into another. This helps to organize and manage code more efficiently, especially in large applications.

Why Do We Need Modules?

1.   Modules allow you to break your code into smaller, manageable parts. This makes it easier to work on, test, and maintain.

2.   Code in a module can be reused across different files or even projects.

3.   Variables and functions in a module are not visible to the global scope, so you can avoid polluting the global namespace and creating conflicts between different pieces of code.

4.   Large applications are easier to maintain when code is divided into logical modules, making it simpler to locate and update specific functionality.

 

What Can I Export from a Module?

1.   Functions: Logic pieces that perform a task.

2.   Variables/Constants: Pieces of data or values.

3.   Objects: Complex data structures, such as arrays or object literals.

4.   Classes: Templates for creating objects in an organized manner.

 

How to Export in JavaScript?

Exporting multiple items, each with its own name.

 

arithmetic.js 

export function add(a, b){
    return a + b;
}

function subtract(a, b){
    return a - b;
}

export const PI = 3.14;

 

How to Import in JavaScript?

To import from a module, you need to reference the file path and import the items you want.

import {add, PI} from "./arithmetic.js"

 

The .js extension is mandatory when importing modules in modern JavaScript, especially in browsers and environments that natively support ES modules (such as recent versions of Chrome, Firefox, and Node.js). If you omit the .js extension, you will likely encounter an error.

 

arithmetic-demo.js

import {add, PI} from "./arithmetic.js"

console.log(`Sum of 10 and 20 is ${add(10, 20)}`);
console.log(`Value of PI is ${PI}`)

 

Output

Sum of 10 and 20 is 30
Value of PI is 3.14

 

 

Previous                                                    Next                                                    Home

No comments:

Post a Comment