About Lesson
Exporting in JavaScript Modules?
Modules allow you to export variables, functions, or classes from one file so they can be imported into another.
Types of Export:
1. Named Export:
Allows you to export multiple items from a module.
Example:
File: mathUtils.js
JavaScript
// Named exports
export const add = (a, b) => a + b;
export const subtract = (a, b) => a - b;
export const multiply = (a, b) => a * b;
File: main.js
JavaScript
// Import specific functions
import { add, subtract } from './mathUtils.js';
console.log(add(5, 3)); // Output: 8
console.log(subtract(9, 2)); // Output: 7
2. Default Export:
Allows you to export a single item from a module.
Example:
File: greet.js
JavaScript
// Default export
const greet = (name) => `Hello, ${name}!`;
export default greet;
File: main.js
JavaScript
// Import the default export
import greet from './greet.js';
console.log(greet('Manjeet')); // Output: Hello, Manjeet!