In JavaScript, there are several ways to export a function from one module, so you can easily use it in another module. In this blog post, we will explore the two most common methods: using the module.exports and export keywords.
Method 1: Using module.exports
This method is commonly used in Node.js applications, where you have a separate file for each module. It allows you to export a single function, an object containing multiple functions, or even a class.
To demonstrate this, let’s create a simple function called sayHello that we want to export:
function sayHello(name) { console.log(`Hello, ${name}!`); }
To export this function, all you need to do is assign it to the module.exports object:
module.exports = sayHello;
If you want to export multiple functions, you can create an object with the functions as its properties:
function sayGoodbye(name) { console.log(`Goodbye, ${name}!`); } module.exports = { sayHello, sayGoodbye };
To use the exported function(s) in another module, you simply need to require the module and call the function:
const greetings = require('./greetings.js'); greetings.sayHello('John');
Method 2: Using the export keyword (ES6 Modules)
With the introduction of ES6, JavaScript gained a new way of exporting and importing modules called ES6 Modules. This method is more versatile and can be used in both Node.js and modern browsers.
To export a function using ES6 Modules, you simply need to add the export keyword before the function declaration:
export function sayHello(name) { console.log(`Hello, ${name}!`); }
If you want to export multiple functions, you can use the export keyword with each function declaration:
export function sayGoodbye(name) { console.log(`Goodbye, ${name}!`); }
To use the exported function(s) in another module, you can use the import keyword:
import { sayHello } from './greetings.js'; sayHello('John');
Or, if you are importing multiple functions, you can use a single import statement:
import { sayHello, sayGoodbye } from './greetings.js'; sayHello('John'); sayGoodbye('John');
Conclusion
Exporting and importing functions in JavaScript is a fundamental part of modular programming, allowing you to create reusable and maintainable code. Whether you’re using module.exports in a Node.js application or export in ES6 Modules, the process is simple and straightforward, making it easy to share your functions across your entire project.