0
0
Javascriptprogramming~20 mins

Why modules are used in Javascript - See It in Action

Choose your learning style9 modes available
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
1
Create the greeting module
Create a file named greet.js and write a function called sayHello that returns the string 'Hello, friend!'. Export this function using export function sayHello() syntax.
Javascript
Need a hint?

Use export function sayHello() { return 'Hello, friend!'; } to create and export the function.

2
Create the math module
Create a file named math.js and write a function called add that takes two parameters a and b and returns their sum. Export this function using export function add(a, b) syntax.
Javascript
Need a hint?

Use export function add(a, b) { return a + b; } to create and export the function.

3
Import modules in main file
Create a file named main.js. Import the sayHello function from greet.js and the add function from math.js using import { sayHello } from './greet.js' and import { add } from './math.js'.
Javascript
Need a hint?

Use import { sayHello } from './greet.js'; and import { add } from './math.js'; to bring in the functions.

4
Use imported functions and print results
In main.js, call the sayHello() function and print its result using console.log. Then call the add(5, 7) function and print its result using console.log.
Javascript
Need a hint?

Use console.log(sayHello()); and console.log(add(5, 7)); to show the results.