In modern JavaScript, modules are an essential feature that allows you to break down your code into smaller, reusable pieces. This makes your code more maintainable, easier to understand, and helps avoid issues with variable scope and naming conflicts. In this section, we will cover the basics of JavaScript modules, how to use the import
and export
statements, and provide practical examples and exercises.
Key Concepts
- Modules: A module is a file containing JavaScript code. By default, variables and functions defined in a module are not accessible outside the module unless explicitly exported.
- Export: The
export
statement is used to make variables, functions, or classes available to other modules. - Import: The
import
statement is used to bring in variables, functions, or classes from other modules into the current module.
Exporting from a Module
There are two main ways to export from a module: named exports and default exports.
Named Exports
Named exports allow you to export multiple values from a module. Each value must be explicitly exported.
// math.js export const PI = 3.14159; export function add(a, b) { return a + b; } export function subtract(a, b) { return a - b; }
Default Exports
Default exports are used to export a single value from a module. This value can be a function, class, object, or any other JavaScript value.
Importing from a Module
To use the exported values from a module, you need to import them into another module.
Importing Named Exports
When importing named exports, you must use the same names as the exported values.
// app.js import { PI, add, subtract } from './math.js'; console.log(PI); // 3.14159 console.log(add(2, 3)); // 5 console.log(subtract(5, 2)); // 3
Importing Default Exports
When importing a default export, you can use any name you like for the imported value.
Importing All Named Exports
You can import all named exports from a module using the *
syntax and an alias.
// app.js import * as math from './math.js'; console.log(math.PI); // 3.14159 console.log(math.add(2, 3)); // 5 console.log(math.subtract(5, 2)); // 3
Practical Example
Let's create a simple example to demonstrate the use of modules, import, and export.
Step 1: Create the math.js
Module
// math.js export const PI = 3.14159; export function add(a, b) { return a + b; } export function subtract(a, b) { return a - b; }
Step 2: Create the calculator.js
Module
Step 3: Create the app.js
Module
// app.js import { PI, add, subtract } from './math.js'; import multiply from './calculator.js'; console.log(`PI: ${PI}`); // PI: 3.14159 console.log(`2 + 3 = ${add(2, 3)}`); // 2 + 3 = 5 console.log(`5 - 2 = ${subtract(5, 2)}`); // 5 - 2 = 3 console.log(`2 * 3 = ${multiply(2, 3)}`); // 2 * 3 = 6
Exercises
Exercise 1: Create and Use a Module
- Create a new module named
geometry.js
. - In
geometry.js
, define and export two functions:areaOfCircle(radius)
andcircumferenceOfCircle(radius)
. - In
app.js
, import the functions fromgeometry.js
and use them to calculate the area and circumference of a circle with a radius of 5.
Solution
// geometry.js export function areaOfCircle(radius) { return Math.PI * radius * radius; } export function circumferenceOfCircle(radius) { return 2 * Math.PI * radius; } // app.js import { areaOfCircle, circumferenceOfCircle } from './geometry.js'; const radius = 5; console.log(`Area of circle: ${areaOfCircle(radius)}`); // Area of circle: 78.53981633974483 console.log(`Circumference of circle: ${circumferenceOfCircle(radius)}`); // Circumference of circle: 31.41592653589793
Exercise 2: Default Export
- Create a new module named
converter.js
. - In
converter.js
, define and export a default functioncelsiusToFahrenheit(celsius)
. - In
app.js
, import the default function fromconverter.js
and use it to convert 25 degrees Celsius to Fahrenheit.
Solution
// converter.js export default function celsiusToFahrenheit(celsius) { return (celsius * 9/5) + 32; } // app.js import celsiusToFahrenheit from './converter.js'; const celsius = 25; console.log(`${celsius}°C is ${celsiusToFahrenheit(celsius)}°F`); // 25°C is 77°F
Summary
In this section, we covered the basics of JavaScript modules, including how to use the import
and export
statements. We learned about named exports, default exports, and how to import them into other modules. By breaking down your code into modules, you can create more maintainable and reusable code. In the next section, we will dive into asynchronous JavaScript with callbacks.
JavaScript: From Beginner to Advanced
Module 1: Introduction to JavaScript
- What is JavaScript?
- Setting Up Your Development Environment
- Your First JavaScript Program
- JavaScript Syntax and Basics
- Variables and Data Types
- Basic Operators
Module 2: Control Structures
Module 3: Functions
- Defining and Calling Functions
- Function Expressions and Arrow Functions
- Parameters and Return Values
- Scope and Closures
- Higher-Order Functions
Module 4: Objects and Arrays
- Introduction to Objects
- Object Methods and 'this' Keyword
- Arrays: Basics and Methods
- Iterating Over Arrays
- Array Destructuring
Module 5: Advanced Objects and Functions
- Prototypes and Inheritance
- Classes and Object-Oriented Programming
- Modules and Import/Export
- Asynchronous JavaScript: Callbacks
- Promises and Async/Await
Module 6: The Document Object Model (DOM)
- Introduction to the DOM
- Selecting and Manipulating DOM Elements
- Event Handling
- Creating and Removing DOM Elements
- Form Handling and Validation
Module 7: Browser APIs and Advanced Topics
- Local Storage and Session Storage
- Fetch API and AJAX
- WebSockets
- Service Workers and Progressive Web Apps (PWAs)
- Introduction to WebAssembly
Module 8: Testing and Debugging
Module 9: Performance and Optimization
- Optimizing JavaScript Performance
- Memory Management
- Efficient DOM Manipulation
- Lazy Loading and Code Splitting
Module 10: JavaScript Frameworks and Libraries
- Introduction to React
- State Management with Redux
- Vue.js Basics
- Angular Basics
- Choosing the Right Framework