Interview question
What are ES6 modules and how do import/export work? ES6 modules क्या हैं और import/export कैसे काम करते हैं?
Answer
ES6 modules provide a native, standardized way to split code into reusable files, each with its own scope, replacing older patterns like CommonJS or IIFE-based modules.
// math.js - named exports
export function add(a, b) {
return a + b;
}
export function subtract(a, b) {
return a - b;
}
export const PI = 3.14159;
// Alternative: export all at once at the bottom
function multiply(a, b) { return a * b; }
export { multiply };
// main.js - importing named exports
import { add, subtract, PI } from './math.js';
console.log(add(2, 3)); // 5
console.log(PI); // 3.14159
// Renaming imports
import { add as sum } from './math.js';
console.log(sum(2, 3)); // 5
// Importing everything as a namespace object
import * as MathUtils from './math.js';
console.log(MathUtils.add(2, 3)); // 5
// user.js - default export (one per file)
export default class User {
constructor(name) {
this.name = name;
}
}
// Importing a default export - name can be anything
import User from './user.js';
const u = new User('John');
// Combining default and named exports
export default function App() {}
export const VERSION = '1.0.0';
import App, { VERSION } from './app.js';
// Dynamic imports - loaded on demand, returns a Promise
async function loadModule() {
const module = await import('./math.js');
console.log(module.add(1, 2)); // 3
}
// Modules are singletons - imported only once, state is shared across all importers
// and modules run in strict mode automatically, with their own top-level scopeES6 modules code को reusable files में split करने का native, standardized तरीका देते हैं, हर एक का अपना scope होता है।
// math.js - named exports
export function add(a, b) {
return a + b;
}
export function subtract(a, b) {
return a - b;
}
export const PI = 3.14159;
// main.js - named exports import करना
import { add, subtract, PI } from './math.js';
console.log(add(2, 3)); // 5
// Import rename करना
import { add as sum } from './math.js';
// सब कुछ namespace object की तरह import करना
import * as MathUtils from './math.js';
console.log(MathUtils.add(2, 3));
// user.js - default export (एक file में एक)
export default class User {
constructor(name) {
this.name = name;
}
}
import User from './user.js'; // कोई भी नाम रख सकते हैं
// Default और named export साथ
export default function App() {}
export const VERSION = '1.0.0';
import App, { VERSION } from './app.js';
// Dynamic imports - on demand, Promise return करता है
async function loadModule() {
const module = await import('./math.js');
console.log(module.add(1, 2));
}Was this answer clear?