Export and Import in JavaScript: A Step-by-Step Guide
Hey there, coder! Are you ready to learn about one of the most powerful features in JavaScript: exporting and importing modules? In this tutorial, we'll explore how to export a function from a module and import it into another file.
Step 1: Create a New Module
Open your index.js
file and create a new module by adding the following code:
// index.jsfunction greet(name) { console.log(`Hello, ${name}!`)}
export { greet }
Here, we've defined a greet
function that takes a name
parameter and logs a greeting message to the console. We've also used the export
keyword to make the greet
function available for import in other files.
Step 2: Create a New File and Import the Module
Create a new file called main.js
and add the following code:
// main.jsimport { greet } from "./index.js"
greet("Alice")
Here, we've imported the greet
function from the index.js
file using the import
statement. We've also called the greet
function with the argument 'Alice'
.
Step 3: Run the Code
Click the "Run" button to execute the code. You should see the following output in the console:
Hello, Alice!
How it Works
When we exported the greet
function from index.js
, we made it available for import in other files. In main.js
, we imported the greet
function using the import
statement, which allows us to use the function as if it were defined locally.
Real-World Example
Imagine you're building a web application that requires a utility function to format dates. You can create a separate module for the date formatter and export it for use in other parts of the application.
Tips and Variations
as
keyword to alias the imported value.What's Next?
Now that you've learned about exporting and importing modules, try creating your own modules and importing them into other files. Experiment with different export and import statements to see how they work.
Challenge
Create a new module that exports a function to calculate the area of a rectangle. Then, import the function into a new file and use it to calculate the area of a rectangle with a length of 5 and a width of 3.
When you're ready, click the "Run" button to see the output. Happy coding!
Tests