Introduction to Modules

Modules are reusable pieces of code that can be imported and exported between different files. This promotes code organization, maintainability, and code reuse. ES6 introduced a standardized module system, which can be used with the import and export statements.

Exporting from a Module

// utils.js
export const PI = 3.14159;
export function calculateCircumference(radius) {
return 2 * PI * radius;
}
export default function calculateArea(radius) {
return PI * radius ** 2;
}

Importing into a Module

// main.js
import calculateArea, { calculateCircumference, PI } from './utils.js';
console.log(PI); // 3.14159
console.log(calculateCircumference(5)); // 31.4159
console.log(calculateArea(5)); // 78.53975

Destructuring Assignment

Destructuring assignment is a concise syntax for extracting values from arrays or properties from objects and assigning them to variables.

const person = { name: 'John', age: 30 };
const { name, age } = person;
console.log(name); // 'John'
console.log(age); // 30
const [a, b, c] = [1, 2, 3];
console.log(a); // 1
console.log(b); // 2
console.log(c); // 3

Spread and Rest Operators

The spread operator (...) allows you to spread the elements of an iterable (like an array) into individual elements, while the rest operator collects multiple elements into an array.

const numbers = [1, 2, 3];
const newNumbers = [...numbers, 4, 5];
console.log(newNumbers); // [1, 2, 3, 4, 5]
const [first, ...rest] = newNumbers;
console.log(first); // 1
console.log(rest); // [2, 3, 4, 5]

Template Literals

Template literals are a new way of creating strings in ES6. They allow for string interpolation and multi-line strings without the need for concatenation.

const name = 'John';
const age = 30;
console.log(Hello, my name is ${name} and I'm ${age} years old.);
// Hello, my name is John and I'm 30 years old.
const multiLineString = This is a multi-line string.;
console.log(multiLineString);
/*
This is
a multi-line
string.
*/

Promises and Async/Await

Promises are objects that represent the eventual completion (or failure) of an asynchronous operation and its resulting value. The async/await syntax provides a more readable way to work with Promises.

function fetchData() {
return new Promise((resolve, reject) => {
setTimeout(() => {
const data = { name: 'John', age: 30 };
resolve(data);
}, 2000);
});
}
async function getData() {
try {
const data = await fetchData();
console.log(data); // { name: 'John', age: 30 }
} catch (error) {
console.error(error);
}
}
getData();

In the next chapter, we'll take a look at popular JavaScript libraries and frameworks, as well as testing frameworks.