Learn how to share functions between JavaScript files using ES6 export and import statements. Understand named and default exports, module scope, and encapsulation.
In modern JavaScript development, organizing code into modules is essential for maintaining clean, manageable, and scalable applications. Modules allow us to break down complex programs into smaller, reusable pieces. In this section, we will explore how to export and import functions using ES6 module syntax, which is now a standard part of JavaScript.
Modules are self-contained units of code that can be reused across different parts of an application. They help in encapsulating functionality, making code more maintainable and easier to understand. In JavaScript, modules can export certain values, functions, or objects, which can then be imported and used in other modules.
Exporting functions from a module allows them to be used in other modules. There are two primary ways to export functions in JavaScript: named exports and default exports.
Named exports allow you to export multiple functions, variables, or objects from a module. Each exported entity must be explicitly named.
Syntax:
// myModule.js
// Named export of a function
export function greet(name) {
return `Hello, ${name}!`;
}
// Named export of a variable
export const PI = 3.14159;
In the example above, we have a module myModule.js
that exports a function greet
and a constant PI
. These can be imported individually by their names.
A default export allows a module to export a single value or function. This is useful when a module is designed to export one primary thing.
Syntax:
// mathOperations.js
// Default export of a function
export default function add(a, b) {
return a + b;
}
Here, mathOperations.js
exports a default function add
. A module can have only one default export.
Once functions are exported from a module, they can be imported into other modules using the import
statement.
To import named exports, you must use the exact names of the exported entities.
Syntax:
// main.js
// Importing named exports
import { greet, PI } from './myModule.js';
console.log(greet('Alice')); // Output: Hello, Alice!
console.log(PI); // Output: 3.14159
In this example, we import the greet
function and PI
constant from myModule.js
into main.js
.
Default exports can be imported with any name, as they are the primary export of the module.
Syntax:
// app.js
// Importing a default export
import add from './mathOperations.js';
console.log(add(5, 3)); // Output: 8
Here, the add
function is imported from mathOperations.js
and can be used directly.
A module can have both named and default exports. You can import them together as needed.
Example:
// utilities.js
// Named export
export function subtract(a, b) {
return a - b;
}
// Default export
export default function multiply(a, b) {
return a * b;
}
// app.js
// Importing both named and default exports
import multiply, { subtract } from './utilities.js';
console.log(multiply(4, 2)); // Output: 8
console.log(subtract(10, 5)); // Output: 5
Modules in JavaScript have their own scope. Variables and functions declared within a module are not accessible outside unless they are exported. This encapsulation helps prevent naming conflicts and keeps the global namespace clean.
// scopedModule.js
// This variable is private to the module
const privateVariable = 'I am private';
// This function is also private
function privateFunction() {
console.log('This is a private function');
}
// Exported function
export function publicFunction() {
console.log('This is a public function');
}
In scopedModule.js
, privateVariable
and privateFunction
are not accessible outside the module, while publicFunction
is exported and can be used in other modules.
Let’s build a simple calculator using modules to demonstrate exporting and importing functions.
Step 1: Create a Module for Basic Operations
// operations.js
// Named exports for basic operations
export function add(a, b) {
return a + b;
}
export function subtract(a, b) {
return a - b;
}
export function multiply(a, b) {
return a * b;
}
export function divide(a, b) {
if (b === 0) {
throw new Error('Cannot divide by zero');
}
return a / b;
}
Step 2: Create a Main Module to Use the Operations
// calculator.js
// Importing named exports from operations.js
import { add, subtract, multiply, divide } from './operations.js';
function calculate() {
console.log('Addition:', add(10, 5)); // Output: 15
console.log('Subtraction:', subtract(10, 5)); // Output: 5
console.log('Multiplication:', multiply(10, 5)); // Output: 50
console.log('Division:', divide(10, 5)); // Output: 2
}
calculate();
When working with modules, it’s important to consider how functions and variables are scoped and encapsulated. Here are some key points to keep in mind:
Experiment with exporting and importing functions by creating your own modules. Try the following:
capitalize
and reverseString
.To better understand how modules interact, let’s visualize the flow of exporting and importing functions using a diagram.
graph TD; A[operations.js] -->|exports| B[add, subtract, multiply, divide]; B -->|imports| C[calculator.js]; C --> D[calculate function]; D --> E[Console Output];
Diagram Description: This diagram shows the operations.js
module exporting functions, which are then imported into calculator.js
. The calculate
function in calculator.js
uses these imported functions to produce console output.
For further reading and deeper understanding, consider exploring the following resources:
Before we wrap up, let’s test your understanding of exporting and importing functions with a few questions:
Remember, mastering modules and understanding how to export and import functions is a crucial step in becoming proficient in JavaScript. As you continue to explore and experiment, you’ll find that modules greatly enhance the structure and maintainability of your code. Keep practicing, stay curious, and enjoy the journey of learning JavaScript!