Exporting a Function in JavaScript
In JavaScript, it is common to divide a program into separate files. So, when we define a function in one file, how can we make it accessible to other files?
To export a function, you can define it like this:
1 | function sum(a, b) { |
To make this function available in other files, you can use the following syntax to export it as the default export:
1 | export default sum; |
This is referred to as a default export.
In the files that require this exported function, you can import it using the following syntax:
1 | import sum from 'myfile'; |
By using this approach, you can easily share and reuse functions across multiple JavaScript files.
Tags: JavaScript, export function, default export, import