How do you import and export modules?

JavaScript

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

// 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;
// app.js — named imports (must match export names)
import { add, subtract, PI } from './math.js';

You can rename on import:

import { add as sum } from './math.js';
sum(1, 2); // 3

Default exports and imports

// Button.js — default export (one per file)
export default function Button({ children }) {
return <button>{children}</button>;
}
// App.js — default import (any name works)
import Button from './Button.js';
import MyButton from './Button.js'; // also works

Combining both

// api.js
export default function fetchData() {
/* ... */
}
export function formatResponse(data) {
/* ... */
}
// app.js
import fetchData, { formatResponse } from './api.js';

Re-exporting

Useful for creating barrel files (index.js that re-exports from multiple files):

// components/index.js
export { default as Button } from './Button.js';
export { default as Input } from './Input.js';
export { default as Modal } from './Modal.js';
// Now import from one place
import { Button, Input, Modal } from './components';

Dynamic imports

Load modules on demand:

const module = await import('./heavy-library.js');
module.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.