How do you import and export modules?
The short answer
Use export to share code from a file and import to use it in another. Named exports use curly braces on import, default exports do not. You can also use export default for the main thing a file provides, and dynamic import() for loading modules on demand.
Named exports and imports
1// math.js — named exports2export function add(a, b) {3 return a + b;4}5export function subtract(a, b) {6 return a - b;7}8export const PI = 3.14159;910// app.js — named imports (must match export names)11import { add, subtract, PI } from './math.js';
You can rename on import:
1import { add as sum } from './math.js';2sum(1, 2); // 3
Default exports and imports
1// Button.js — default export (one per file)2export default function Button({ children }) {3 return <button>{children}</button>;4}56// App.js — default import (any name works)7import Button from './Button.js';8import MyButton from './Button.js'; // also works
Combining both
1// api.js2export default function fetchData() {3 /* ... */4}5export function formatResponse(data) {6 /* ... */7}89// app.js10import fetchData, { formatResponse } from './api.js';
Re-exporting
Useful for creating barrel files (index.js that re-exports from multiple files):
1// components/index.js2export { default as Button } from './Button.js';3export { default as Input } from './Input.js';4export { default as Modal } from './Modal.js';56// Now import from one place7import { Button, Input, Modal } from './components';
Dynamic imports
Load modules on demand:
1const module = await import('./heavy-library.js');2module.doSomething();
Interview Tip
Show named vs default exports with a quick example each. Mention re-exporting for barrel files and dynamic imports for code splitting. This is a syntax question — keep examples short.
Why interviewers ask this
This tests fundamental module syntax knowledge. Interviewers want to confirm you know named vs default exports, how to combine them, and how to organize imports across files.