Lesson 71 – Default Exports in JavaScript Modules
In JavaScript modules, default exports are a special kind of export that allows you to export a single value or function as the default for that module. This makes it easier to import without using curly braces.
What is a Default Export?
A default export lets you export one thing from a module. When importing, you can name it whatever you want.
// file: greet.js
export default function greet(name) {
return `Hello, ${name}!`;
}
Now you can import it like this:
// file: main.js
import sayHello from './greet.js';
console.log(sayHello('Sarah')); // Hello, Sarah!
Notice:
- No curly braces during import.
- The name
sayHello
is arbitrary – you can use any name.
Default Export with Variables
You can also default export a variable:
// file: user.js
const user = {
name: "Ayo",
age: 25
};
export default user;
And import it like:
// file: app.js
import profile from './user.js';
console.log(profile.name); // Ayo
Rules of Default Export
- Only one default export per file.
- You can still use named exports alongside a default export.
// file: data.js
export const age = 30;
export default "Daniel";
// file: main.js
import name, { age } from './data.js';
console.log(name); // Daniel
console.log(age); // 30
Why Use Default Exports?
- Great when your module has one main thing to export.
- Cleaner syntax when importing.
- Lets users name the import as they wish.
Try Your Hand
Exercise:
- Create a module that exports a default function to multiply two numbers.
- Import and use it in another file with any name.
Summary
- Use
export default
for the main value/function in your module. - Import it without
{}
. - Only one default export allowed per module.