🍞Default Export

Optional Topic

In JavaScript, you can use the export default statement to specify a default export for a module. This is useful when you want to export just a single value or object from a module, rather than multiple values.

Here's an example of how you might use a default export:

First, let's define a utility function in a file called math.js:

export default function add(x, y) {
  return x + y;
}

To import this default export in another module, you can use the import keyword followed by any name you want to give the imported value:

import add from './math.js';

console.log(add(1, 2)); // 3

You can also use the import keyword to import the default export along with any named exports from the same module:

import add, { subtract } from './math.js';

console.log(add(1, 2)); // 3
console.log(subtract(5, 3)); // 2

In this example, the add function is the default export, and the subtract function is a named export. You can have as many named exports as you want in a module, but you can only have one default export.

It's also worth noting that you can use the export default statement to export an object, class, or any other value as the default export:

export default class MyClass {
  // ...
}
export default {
  foo: 'bar',
  baz: 'qux'
};

You don't strictly need default exports in JavaScript, as you can use named exports to accomplish the same thing. However, default exports can be a convenient way to specify a single value that will be exported from a module, especially if you don't want to use the same name for the exported value as the name of the variable or function that it came from.

Overall, default exports can provide a more flexible and convenient way to export values from a module, especially when you only want to export a single value or object. However, whether or not you choose to use default exports is up to you and your personal preference.

Last updated