Why modules are used
📖 Scenario: Imagine you are building a simple web app that shows a greeting message and calculates the sum of two numbers. To keep your code clean and organized, you want to separate these two tasks into different files called modules.
🎯 Goal: You will create two JavaScript modules: one for greeting and one for addition. Then you will use these modules in a main file to show the greeting and the sum. This will help you understand why modules are used to organize code better.
📋 What You'll Learn
Create a module file named
greet.js that exports a function called sayHello which returns the string 'Hello, friend!'.Create a module file named
math.js that exports a function called add which takes two numbers and returns their sum.Create a main file named
main.js that imports sayHello from greet.js and add from math.js.In
main.js, call sayHello and print the result, then call add with numbers 5 and 7 and print the result.💡 Why This Matters
🌍 Real World
In real projects, modules help developers work on different parts of a program separately and combine them easily.
💼 Career
Understanding modules is essential for JavaScript developers to write clean, maintainable code and collaborate with others.
Progress0 / 4 steps