It seems like you are using an ad blocker. To enhance your experience and support our website, please consider:

  1. Signing in to disable ads on our site.
  2. Sign up if you don't have an account yet.
  3. Or, disable your ad blocker by doing this:
    • Click on the ad blocker icon in your browser's toolbar.
    • Select "Pause on this site" or a similar option for lancecourse.com.

Javascript in 100 bits

Course by zooboole,

Last Updated on 2025-01-28 08:04:00

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:

  1. Create a module that exports a default function to multiply two numbers.
  2. 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.