- Array() find
- -- operator
- -= operator
- ++ operator
- += operator
- Accessing and setting content
- AND operator
- Array concat() method
- Array indexOf()
- Array length
- Array pop()
- Array shift
- Array slice() method
- Arrays
- Arrow function
- Async await
- Booleans
- Braces
- Callback function
- Calling the function
- Class
- Closure
- Code block
- Comment
- Conditions
- Console
- const
- Constructor
- Creating a p element
- Data types
- Date getTime()
- Destructuring
- DOM
- Else
- Else if
- Enum
- Environment
- Equals operator
- Error Handling
- ES6
- Event listener method
- Event loop
- Events
- Export statement
- Extends
- Fetch API
- Filter
- For loop
- forEach()
- Function
- Function bind()
- Function name
- Greater than
- Head element
- Hoisting
- If statement
- Import statement
- includes()
- Infinity property
- isNaN function
- Iterator
- JSON
- Less than
- Let
- Local storage
- Map
- Methods
- Module
- Modulo operator
- Node.js
- null
- Numbers
- Object
- Object.keys()
- Optional chaining
- Overriding methods
- Parameters
- Promises
- Prototype
- Random
- Reduce
- Regex
- Regular expressions
- Removing an element
- Replace
- Scope
- Session storage
- setInterval
- setTimeout() method
- Sleep() function
- Sort
- Splice
- Spread operator
- String
- String concat()
- String indexOf()
- String slice() method
- Substring
- Switch statement
- Template literals
- Ternary operator
- throw Statement
- Title
- Try catch
- Type conversion
- undefined
- var
- void Operator
- What is JavaScript?
- While loop
JAVASCRIPT
JavaScript Export Statement: Syntax, Usage, and Examples
An export statement in JavaScript lets you share code from one file so other files can import and use it. You use exports to build reusable modules instead of keeping everything trapped in one giant script.
How to Use the Export Statement
The export statement is part of ES Modules (ESM). You place exports in the file that “owns” the code, then you import them somewhere else.
Learn JavaScript on Mimo
Basic syntax
The simplest option is exporting something as a named export:
exportfunctiongreet(name) {
return`Hi, ${name}!`;
}
That function can now be imported from another file.
Exporting variables and constants
You can export values like constants, configuration objects, or shared data.
exportconstTAX_RATE =0.21;
exportconst appName ="Budget Buddy";
These exports stay read-only from the outside, which keeps your settings consistent.
Exporting a class
Classes are commonly exported because they often represent a reusable “thing” in your code.
exportclassTimer {
constructor(seconds) {
this.seconds = seconds;
}
start() {
console.log(`Starting for ${this.seconds} seconds`);
}
}
Exporting a list of items at the end
Instead of adding export in front of each thing, you can export them together.
functionadd(a, b) {
return a + b;
}
functionsubtract(a, b) {
return a - b;
}
export { add, subtract };
This style works well when you want the main logic first, and the exports at the bottom.
Renaming exports
Sometimes you want the export name to look cleaner, or you want to expose a different name than the internal one.
functioncalculateDiscount(price) {
return price *0.1;
}
export { calculateDiscountas discount };
Now other files import discount, even though the function inside the module is called calculateDiscount.
Default exports
A module can also have a default export. You usually use this when the module has one main thing to share.
exportdefaultfunctionformatDate(date) {
return date.toLocaleDateString();
}
Default exports are imported without curly braces, which makes them feel “main character” in the file.
Exporting an existing value as default
You can define something first, then export it as default:
functioncreateId() {
returnMath.random().toString(16).slice(2);
}
exportdefault createId;
Exporting with “as default” in one line
You might see this pattern in some projects:
export { createIdasdefault };
It looks a bit strange at first, but it can be useful when a file already uses named exports and you want to add a default export later.
When to Use the Export Statement
Exports are about teamwork, between files. Even if you’re working solo, your future self counts as a teammate.
1) Splitting a project into modules
When code grows, one file becomes a junk drawer. Exporting helps you split your code into logical pieces like:
api.jsfor network requestsmath.jsfor calculationsui.jsfor DOM updates
Then you import only what you need in each file.
2) Reusing utilities across the app
Functions like formatPrice(), capitalize(), or debounce() can be exported and reused everywhere. That avoids copy-paste bugs.
3) Sharing constants and configuration
Stuff like API URLs, feature flags, and app-wide limits belong in one place. Export them once, then import them where needed.
4) Creating reusable UI components
Many front-end setups treat components as modules. You export a button component, a form component, or an entire page layout, then import them into the main app.
5) Keeping code easier to test
Tests usually import the function or class they need to verify. Clean exports make your testing setup much simpler.
Examples of the Export Statement
Example 1: Exporting helpers for formatting text
Imagine a small app that cleans up user input before saving it.
textUtils.js
exportfunctiontrimExtraSpaces(text) {
return text.trim().replace(/\s+/g," ");
}
exportfunctionmakeTitleCase(text) {
return text
.split(" ")
.map(word => word[0].toUpperCase() + word.slice(1).toLowerCase())
.join(" ");
}
app.js
import { trimExtraSpaces, makeTitleCase }from"./textUtils.js";
const rawName =" maya johnson ";
const cleanName =makeTitleCase(trimExtraSpaces(rawName));
console.log(cleanName);// "Maya Johnson"
This example shows named exports working like a toolbox, pick the tool you want.
Example 2: Exporting a default function for one main job
Sometimes a module has one purpose, like formatting prices.
formatPrice.js
exportdefaultfunctionformatPrice(value) {
return`$${value.toFixed(2)}`;
}
checkout.js
import formatPricefrom"./formatPrice.js";
console.log(formatPrice(3.5));// "$3.50"
No curly braces needed because this is a default export.
Example 3: Exporting a class for reuse
Let’s say you’re building a small productivity app with timers.
PomodoroTimer.js
exportclassPomodoroTimer {
constructor(minutes) {
this.minutes = minutes;
}
start() {
console.log(`Focus time: ${this.minutes} minutes`);
}
}
main.js
import {PomodoroTimer }from"./PomodoroTimer.js";
const focusSession =newPomodoroTimer(25);
focusSession.start();
A class export makes the file feel like a “feature module” you can plug in anywhere.
Example 4: Exporting a shared configuration object
Config values shouldn’t be scattered around like socks in a teenager’s room.
config.js
exportconst config = {
apiUrl:"https://api.example.com",
timeoutMs:5000,
retryCount:2
};
fetchPosts.js
import { config }from"./config.js";
asyncfunctionfetchPosts() {
const response =awaitfetch(`${config.apiUrl}/posts`);
return response.json();
}
fetchPosts();
When the API URL changes, you update one file, and everything keeps working.
Example 5: Exporting from one file to create a clean “public API”
In larger projects, you might group exports into a single file so other parts of the app can import from one place.
math/add.js
exportfunctionadd(a, b) {
return a + b;
}
math/subtract.js
exportfunctionsubtract(a, b) {
return a - b;
}
math/index.js
export { add }from"./add.js";
export { subtract }from"./subtract.js";
Now consumers can do:
import { add, subtract }from"./math/index.js";
This pattern keeps imports clean and makes the folder feel like a mini-library.
Learn More About the Export Statement
Named exports vs default exports
Named exports work best when a module shares multiple things:
exportfunctionparseCsv(text) {}
exportfunctiontoJson(data) {}
Default exports work well when a module has one main value:
exportdefaultfunctionparseCsv(text) {}
A quick mental shortcut:
- Named exports = “this file has multiple useful pieces”
- Default export = “this file is about one main thing”
Can a module have both?
Yes, a file can export both a default export and named exports.
exportdefaultfunctionlogger(message) {
console.log(message);
}
exportfunctionlogError(errorMessage) {
console.error(errorMessage);
}
Then you import like this:
import logger, { logError }from"./logger.js";
This can be helpful, but don’t overdo it. Too many exports in one file can be confusing.
Exporting while declaring vs exporting later
Both of these styles are common:
Export while declaring
exportfunctiongetUsername() {}
Declare first, export later
functiongetUsername() {}
export { getUsername };
The second style can read nicer in longer files because the main logic stays grouped together.
Re-exporting from another file
Re-exporting lets you pass exports through another module without importing them first.
export { formatPrice }from"./formatPrice.js";
This is handy when you’re building an index file that acts like a central hub.
Common export mistakes
Using the wrong import style
// ❌ formatPrice was exported as default, so curly braces are wrong
import { formatPrice }from"./formatPrice.js";
Fix:
import formatPricefrom"./formatPrice.js";
Importing a named export that doesn’t exist
// ❌ utils.js exports "add", not "sum"
import { sum }from"./utils.js";
Fix:
import { add }from"./utils.js";
Forgetting that exports are static
Exports are resolved at load time, so you can’t dynamically change what a module exports based on runtime conditions. If you need conditional loading, use dynamic imports on the import side instead.
Summary
The export statement lets you share functions, variables, and classes across files using ES Modules. Named exports are great for “toolbox” files, default exports are great for one main feature, and re-exporting can keep your imports tidy in bigger projects. Once you start using exports, your codebase stops feeling like a messy desk and starts feeling like a set of drawers where everything has its place.
Join 35M+ people learning for free on Mimo
4.8 out of 5 across 1M+ reviews
Check us out on Apple AppStore, Google Play Store, and Trustpilot