By the end of this lesson, you will understand how to split code with import and export in JavaScript.
When we build big programs, we should keep our code organized. Splitting code with import and export helps manage this. For example, imagine you have a toy box. If you have many toys, it’s easier to keep them separate so you can find what you need. In coding, we use export to share parts of our code from one file and import to use it in another file.
File: math.js
// math.js
export function add(a, b) {
return a + b;
}
export function subtract(a, b) {
return a - b;
}
File: app.js
// app.js
import { add, subtract } from './math.js';
console.log(add(5, 3)); // Output: 8
console.log(subtract(5, 3)); // Output: 2
Output:
8
2
In the first file, math.js, the functions add and subtract are defined and exported. This means you can use them in other files. In the second file, app.js, we import these functions using the import statement. Finally, we call these functions and display the results in the console.
Now it’s your turn! Create a new file called multiply.js. In this file, write a function to multiply two numbers. Export this function. Then, import this function into your app.js and use it to multiply two numbers. Log the result to the console.
File: multiply.js
// multiply.js
export function multiply(a, b) {
return a * b;
}
Now, modify your app.js file:
// app.js
import { add, subtract } from './math.js';
import { multiply } from './multiply.js';
console.log(add(5, 3)); // Output: 8
console.log(subtract(5, 3)); // Output: 2
console.log(multiply(5, 3)); // Output: 15