Borislav Hadzhiev
Last updated: Mar 29, 2022
Check out my new book
Use named exports to export a function in JavaScript, e.g.
export function sum() {}
. The exported function can be imported by using a
named import as import {sum} from './another-file.js'
. You can use as many
named exports as necessary in a file.
Here is an example of exporting a function from a file called another-file.js
.
// 👇️ named export export function sum(a, b) { return a + b; } // 👇️ named export (arrow function) // export const multiply = (a, b) => { // return a * b; // };
Note that using export
on the same line as the function's definition is the
same as exporting the function as an object after it has been declared.
function sum(a, b) { return a + b; } // 👇️ named export (same as previous code snippet) export { sum };
Here is how we would import the function in a file called index.js
.
import {sum} from './another-file.js'; console.log(sum(45, 55)); // 👉️ 100
Make sure to correct the path that points to the another-file.js
module if you
have to. The example above assumes that another-file.js
and index.js
are
located in the same directory.
For example, if you were importing from one directory up, you would do
import {sum} from '../another-file.js'
.
The import/export syntax is called ES6 Modules in JavaScript.
The example above uses a named export and a named import.
The main difference between named and default exports and imports is - you can have multiple named exports per file, but you can only have a single default export.
If you try to use multiple default exports in a single file, you would get an error.
// 👇️ 2 default exports in same file cause error export default function sum(a, b) { return a + b; } const multiply = (a, b) => { return a * b; }; // ⛔️ SyntaxError: Duplicate export of 'default' export default multiply;
IMPORTANT: If you are exporting a variable (or an arrow function) as a default export, you have to declare it on 1 line and export it on the next. You can't declare and default export a variable on the same line.
1
default export and as many named exports as you need in a single file.Let's look at an example that uses both - default and named exports.
// 👇️ default export export default function sum(a, b) { return a + b; } // 👇️ named export export const multiply = (a, b) => { return a * b; };
And here is how you would import the two functions.
// 👇️ default and named imports import sum, {multiply} from './another-file.js'; console.log(sum(250, 250)); // 👉️ 500 console.log(multiply(5, 5)); // 25
Notice that we didn't wrap the default import in curly braces.
We used a default import to import the sum
function and a named import to
import the multiply
function.
Note that you can only have a single default export per file, but you can have as many named exports as necessary.
You also don't have to think about which members are exported with a default or named export.