1.

What is Export Default and Named Export in ES6?

Answer»

With the help of the import STATEMENT, the export statement comes into picture when one needs to export functions, objects, and variables to other JavaScript modules. There are two methods for exporting:

  • Named Export: Named exports are useful when one has to export multiple values. The name of the imported module must match that of the exported module.

Example:

 //file rectangle.jsfunction perimeter(x, y) { return 2 * (x + y);}function area(x, y) { return x * y;}export { perimeter, area }; //while importing the functions in test.jsimport { perimeter, area } from './rectangle;console.log(perimeter(4, 6)) //20console.log(area(4, 6)) //24

Output:

2024
  • Default Export: There is only one default export per module when it comes to default exports. A function, a class, an OBJECT, or ANYTHING else can be used as a default export. In default export, the naming of imports is fully autonomous, and we can choose any name we like.

Example:

 // file module.jsvar a = 6; export default a; // test.js// while importing a in test.jsimport b from './module'; console.log(b); // output will be 6

Output:

 6
  • Using Named and Default Exports at the same time: In the same file, you can utilise both Named and Default exports. It means they'll both be imported into the same document.
 //index.jsvar a = 3;CONST b = 8;function show() { return "This is a default export."}function product(a , b) { return a * b;}export { show as default, a, b, product };//test.js fileimport any_other_name, { a, b, product} from './index.js';console.log(any_other_name()); //This is a default export.console.log(a); //3

Output:

This is a default export.3


Discussion

No Comment Found