How to Export Multiple Functions in JavaScript
Table of Contents
When you are writing a large program, you'll want to be break up the logic into different files.
This helps you organize your code and makes it easier to read.
In JavaScript, the modern way to do this is to use the import
/export
syntax.
This is when you export a function or variable to be imported in another file.
In this post, we'll learn how to export multiple functions in JavaScript.
Exporting functions
Let's start with two simple example functions to export, in a file called math.js
:
JAVASCRIPTconst add = (a, b) => a + b;
const subtract = (a, b) => a - b;
We can now export both of these functions to be imported in another file.
JAVASCRIPTconst add = (a, b) => a + b;
const subtract = (a, b) => a - b;
export { add, subtract };
This makes it accessible from the outside.
Importing functions
Now that we've exported functions in our file, we can import them in another file.
This allows us to use these functions despite coming from a different file.
Now let's see how to import these functions:
JAVASCRIPTimport { add, subtract } from './math.js';
That's it, now they can be used just like any other function.
JAVASCRIPTimport { add, subtract } from './math.js';
const result = add(1, 2);
console.log(result);
BASH3
Conclusion
In this post, we learned how to export multiple functions in JavaScript.
When you export the functions in one file, you can then import them in another file.
Thanks for reading and happy coding!
- Create an RSS Reader in Node
- How to Set Up Cron Jobs in Linux
- How to deploy a .NET app using Docker
- How to deploy a MySQL Server using Docker
- How to deploy a Node app using Docker
- Learn how to use v-model with a custom Vue component
- How to Scrape the Web using Node.js and Puppeteer
- Getting Started with Handlebars.js
- Getting User Location using JavaScript's Geolocation API
- Getting Started with Moment.js
- Learn how to build a Slack Bot using Node.js
- Setting Up Stylus CSS Preprocessor