In this tutorial, you will be learning Javascript, how to export a function, Syntax, Example codes using Export functions. The export
statement is utilized when building JavaScript modules to export live bindings to functions, objects, or primitive values from the module so they can be done by other programs with the import statement. Export and import functions in Javascript directives have different syntax variants.
- JavaScript Export Function
- Export Syntax
- 1. Named Export Syntax
- 2. Default Export Syntax
- Import Function Syntax
- Example Using Named Exports
- Example Using Default Exports
- Export apart from declarations
- Export before declarations
JavaScript Export Function
In JavaScript, we can separate a program into separate files. How do we make a function we define in a file available to other files?
You typically write a function, like below
function sum(a, b) { return a + b }
Export Syntax
We have two types of exports in Javascript:
- Named Exports (Zero or more exports per module)
- Default Exports (One per module)
1. Named Export Syntax
// Export list export { name1, name2, …, nameN };
2. Default Export Syntax
Also, you can make it possible for any other file with the help of this javascript export function syntax
export default sum
The above syntax code defines the default export function.
Also Check:
Import Function Syntax
The files that need the function exported will import it using this syntax
import sum from 'myfile'
Sample Code Using Named Exports
// export features declared earlier export { myFunction, myVariable }; // export individual features (can export var, let, // const, function, class) export let myVariable = Math.sqrt(2); export function myFunction() { ... };
Sample Code using Default Exports
// module "my-module.js" export default function cube(x) { return x * x * x; }
Export apart from declarations
Moreover, we can place export
separately.
Here we first declare, and then export:
// say.js function sayHi(user) { alert(`Hello, ${user}!`); } function sayBye(user) { alert(`Bye, ${user}!`); } export {sayHi, sayBye}; // a list of exported variables
Or, technically we could placeexport
above functions as well.
Export before declarations
We can identify any declaration as exported by puttingexport
before it, be it a variable, function, or a class.
For example, below all exports are valid:
// export an array export let months = ['Jan', 'Feb', 'Mar','Apr', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec']; // export a constant export const MODULES_BECAME_STANDARD_YEAR = 2015; // export a class export class User { constructor(name) { this.name = name; } }