How to Use Export Default in JavaScript

The export function is useful when we want multiple functions, variables, classes, or any object so that some other program or module can reuse them. In all these scenarios, we use export default.

There are two ways we can export. One way is Names exports, and the other one is Default exports.

  1. Named Exports
  2. Default Exports

Named Exports in JavaScript

Named exports in JavaScript are used when we want to export multiple values/objects/functions etc. While using the named exports, we need to use the same name as the corresponding object.

To use ES6 import and export in Node.js, create a package.json file and add the following code inside it.

 "type": "module",

That way, Node.js will allow us to use ES6 Imports.

Now, create a sqcube.js file and add the following code.

function findSquare(x) {
   return x * x;
function findCube(x) {
   return x * x * x;

export { findSquare as square, findCube as cube };

Here, you can see that we defined two functions and exported two functions like square and cube.

Now, import these two functions inside the app.js file.

import { square, cube } from './sqcube.js';


Now, run the file as a node app in the terminal or cmd, and it will give the output like below.



We created two JavaScript files, sqcube.js, and app.js. In the sqcube.js file, we created two functions that take a number and calculate and return its square and cube. And then, we export the results as shown in the code above. 

Export default in JavaScript

Default exports in JavaScript are useful in a single object, function, or variable. During the import, we can use any name to import. The export statement is used when creating JavaScript modules to export live bindings to functions, objects, or primitive values from the module so other programs with the import statement can use them.

Write the following code inside the sqcube.js file.

export default function findCube(x) {
 return x * x * x;

Now, write the following code inside the app.js.

import square from './sqcube.js';




In sqcube.js, we define a function with the “export default” keyword to make it the default export. We can’t export defaults in more than one module in math.js. In the app.js file, we import the function with a different name (cube), proving that we can import default export functions with any name we want.  And then, we print the result using the console.log() function.

That’s it for how to use export default in JavaScript.

See also

JavaScript import vs require

How to Read a JSON file in JavaScript

How to Write a File in JavaScript

Leave a Comment