What is export default in JavaScript ? (original) (raw)

Last Updated : 10 Jan, 2025

JavaScript modules allow you to organize code into separate files, making it easier to maintain and reuse. To share code between modules, JavaScript provides two types of exports: **Named Exports and Default Exports. Understanding how and when to use these export types is key to effectively managing modular code.

**1. Named Exports

Named exports are used when you want to export multiple values from a module. Each exported value must be imported by its exact name, which enforces consistency and clarity in your code.

Syntax:

// Exporting individual features

export let name1 = …, name2 = …, …, nameN; // also var, const

// Export list

export { name1, name2, …, nameN };

//Exporting everything at once

export { object, number, x, y, boolean, string }

// Renaming exports

export { variable1 as name1, variable2 as name2, …, nameN };

// export features declared earlier

export { myFunction, myVariable };

**Example: In this example, we are exporting everything by their default name.

javascript `

//file math.js function square(x) { return x * x; } function cube(x) { return x * x * x; } export { square, cube };

//while importing square function in test.js import { square, cube } from './math; console.log(square(8)) //64 console.log(cube(8)) //512

`

**Output:

64
512

**Default Exports

Default exports are used when you want to export a single primary object, function, or variable from a module. This type of export allows you to import the value using any name, providing flexibility and simplifying the import process for the module's main content.

**Example: In this example, we are exporting the variable by using "export default" keywords.

javascript `

// file module.js let x = 4; export default x;

// test.js // while importing x in test.js import y from './module'; // note that y is used import x instead of // import x, because x was default export console.log(y); // output will be 4

`

**Output:

4

**Using Named and Default Exports at the same time

JavaScript allows you to use both named and default exports in the same module. This flexibility is helpful when you have a primary export along with additional supporting exports.

**Example: In this example, we are exporting the function.

javascript `

//module.js let x = 2; const y = 4; function fun() { return "This a default export." } function square(x) { return x * x; } export { fun as default, x, y, square };

`

While importing this module.js we can use any name for fun because it is a default export and curly braces for other named exports.

javascript `

//test.js file import anyname, { x, y, square} from './module.js'; console.log(anyname()); //This is a default export. console.log(x); //2

`

**Output:

This is a default export.
2