In this blog, we will discuss how to import and export functions in JavaScript.
In JavaScript, there are different ways to import and export functions. Here are 2 common ways:
- Default Export
- Named Exports
1. Default Export
// greet.js
export default function greet(name) { // EXPORT
console.log(`Hello, ${name}!`);
}
// app.js
import greet from './greet.js'; // IMPORT
greet('Sam');
In this example, we're exporting a function using the export default syntax. This allows us to import the function using any name we want in the importing file, and it doesn't require us to use curly braces when importing.
NOTE: The export default syntax allows you to export only a single value from a module as the default export.
2. Named Exports
// math.js
export function add(a, b) { // EXPORT
return a + b;
}
export function subtract(a, b) { // EXPORT
return a - b;
}
// app.js
import { add, subtract } from './math.js'; // IMPORTS
console.log(add(3, 4));
console.log(subtract(5, 2));
In this example, we're exporting two functions (add and subtract) using the named exports syntax. To import these functions, we need to use curly braces and specify the names of the functions we want to import.
NOTE: While importing, the Name of the function should be the same as defined.
OR
Export all function in one line.
// math.js
function add(a, b) {
return a + b;
}
function subtract(a, b) {
return a - b;
}
export { add, subtract }; // EXPORT ALL FUNTION IN ONE LINE
// app.js
import { add, subtract } from './math.js'; // IMPORT
console.log(add(2, 3));
console.log(subtract(5, 3));
Top comments (0)