JavaScript export vs export default

JavaScript export vs export default

In JavaScript, export and export default is used to export values from a module, making them accessible to other modules. The difference lies in how you import these values into other files.

  1. export statement:

    • When you use export without default, you can export multiple values from a module.

    • For example

// module.js
export const name = "John";
export const age = 30;

To import these values in another file, you need to destructure them or import them using the same names:

// anotherFile.js
import { name, age } from "./module";
  1. export default statement:

    • When you use export default, you are exporting only one value from a module.

    • For example:

// module.js
const person = {
  name: "John",
  age: 30
};
export default person;
  • To import the default export, you can give it any name you want during import. It does not need to have the same name as the exported variable:
// anotherFile.js
import anyName from "./module";

In summary:

  • export is used for exporting multiple values from a module. You import them by their names.

  • export default is used for exporting a single value from a module. You import it with any name of your choice.

You can also have a mix of both in a module, but there can be only one export default statement in a module.