Named exports vs Default exports

Named exports vs Default exports

In JavaScript, there are two ways to export values from a module:

  1. Named exports and

  2. default exports

Named export

A named export allows you to export one or more values from a module using a specific name. This means that when you import the exported values into another module, you need to refer to them by their exported name. Here's an example:

// myModule.js
export const foo = 'foo';
export function bar() {
  console.log('bar');
}

In this example, the module exports two named values: a constant named foo and a function named bar. You can import these values into another module using the import statement.

// main.js
import { foo, bar } from './myModule.js';
console.log(foo); // logs 'foo'
bar(); // logs 'bar'

Note that when importing named exports, you need to use curly braces and the specific name of the export inside them.

Default export

A default export allows you to export a single value from a module as the default value. This means that when you import the exported value into another module, you can choose any name you want for it. Here's an example:

// myModule.js
export default function() {
  console.log('Hello World!');
}

In this example, the module exports a single function as the default value. You can import this value into another module using the import statement:

// main.js
import myFunction from './myModule.js';
myFunction(); // logs 'Hello World!'

Note: that when importing a default export, you can use any name you want for the imported value.

In summary, named exports allow you to export one or more values from a module using specific names, while default exports allow you to export a single value as the default value, which can be imported using any name.

  • Named export: specific name, curly braces {}, n number of exports

  • Default exports: any name, only one

The main use of default exports is to simplify the import syntax when there is only one main value to export from a module. Instead of requiring the user to specify the name of the exported value when importing, the default export allows them to import the value using any name they choose.

Note that a module can have only one default export, and it can be any value, such as a function, a class, an object, or a primitive value. Additionally, you can also combine named and default exports in the same module, as needed.