ES6 Modules 🎯

beginner
5 min

ES6 Modules 🎯

Welcome to our in-depth guide on ES6 Modules! By the end of this tutorial, you'll have a solid understanding of how to use these powerful features to structure your JavaScript projects more efficiently.

Let's start with the basics:

What are ES6 Modules? 📝

ES6 Modules are a modern way to write and manage JavaScript code. They allow you to break down a large project into smaller, more manageable pieces, making it easier to maintain and understand.

Why Use ES6 Modules? 💡

  1. Code Organization: Modules help keep your code clean and organized, making it easier to work with large projects.
  2. Avoiding Naming Conflicts: When you use modules, you don't have to worry about naming conflicts, as each module has its own private namespace.
  3. Better Performance: Modules improve performance by only loading the necessary code when it's needed.

Understanding ES6 Modules 📝

Importing a Module

To import a module, use the import keyword followed by the module name.

javascript
// Import a module named 'myModule' import { functionName } from 'myModule';

In the above example, we're importing a function named functionName from the myModule file.

Exporting a Module

To make a function, class, or variable available to other modules, use the export keyword.

javascript
// myModule.js export function functionName() { // Your code here }

In the above example, we've created a module named myModule and exported a function named functionName.

Advanced ES6 Modules 💡

Default Exports

If a module has only one default export, you can import it using the import keyword without curly braces.

javascript
// myModule.js export default function functionName() { // Your code here } // Import the default export import functionName from 'myModule';

Named Exports

You can also export multiple functions, classes, or variables from a single file using named exports.

javascript
// myModule.js export function function1() { // Your code here } export function function2() { // Your code here }

To import named exports, use the curly braces syntax.

javascript
// Import named exports import { function1, function2 } from 'myModule';

Practical Application 🎯

Let's create a simple example of a calculator module that exports two functions: add and subtract.

calculator.js

javascript
export function add(a, b) { return a + b; } export function subtract(a, b) { return a - b; }

index.js

javascript
import { add, subtract } from './calculator'; console.log(add(5, 3)); // Output: 8 console.log(subtract(5, 3)); // Output: 2

Quiz Time 🎯

Quick Quiz
Question 1 of 1

Which keyword is used to import a module in ES6?

Quick Quiz
Question 1 of 1

What does the `export` keyword do in ES6 Modules?

Quick Quiz
Question 1 of 1

How do you import the default export from a module?

Happy learning! 🎉