Module 11: ES6 Features
Objective: Learn modern JavaScript features introduced in ES6 (ECMAScript 2015), including let and const, template literals, arrow functions, destructuring, default parameters, and more.
1. let and const
let and const provide better ways to declare variables compared to var.
Differences Between let, const, and var
| Feature | let | const | var |
|---|---|---|---|
| Scope | Block-scoped | Block-scoped | Function-scoped |
| Reassignment | Allowed | Not allowed | Allowed |
| Redeclaration | Not allowed | Not allowed | Allowed |
Example:
// Using let let name = "Alice"; name = "Bob"; // Allowed // Using const const age = 25; // age = 30; // Error: Assignment to constant variable // Using var var city = "Paris"; var city = "London"; // Allowed but not recommended
2. Template Literals
Template literals allow you to embed variables and expressions into strings using backticks (`) and ${}.
Example:
let name = "Alice"; let age = 25; console.log(`My name is ${name} and I am ${age} years old.`);
Multiline Strings:
let message = `This is a multiline string using template literals.`; console.log(message);
3. Arrow Functions
Arrow functions provide a shorter syntax for writing functions. They do not have their own this context, which can simplify code.
Syntax:
let functionName = (parameter1, parameter2) => { // Function body };
Example:
let add = (a, b) => a + b; console.log(add(5, 3)); // Outputs: 8
No Parameters:
let greet = () => console.log("Hello!"); greet(); // Outputs: Hello!
4. Default Parameters
Default parameters allow you to set default values for function arguments.
Example:
function greet(name = "Guest") { console.log(`Hello, ${name}!`); } greet(); // Outputs: Hello, Guest! greet("Alice"); // Outputs: Hello, Alice!
5. Destructuring
Destructuring allows you to extract values from arrays or objects into separate variables.
Array Destructuring:
let fruits = ["apple", "banana", "cherry"]; let [first, second] = fruits; console.log(first); // Outputs: apple console.log(second); // Outputs: banana
Object Destructuring:
let person = { name: "Alice", age: 25 }; let { name, age } = person; console.log(name); // Outputs: Alice console.log(age); // Outputs: 25
6. Spread and Rest Operators
The ... operator can be used to expand arrays or objects (spread) or collect multiple elements into an array (rest).
Spread Operator:
let numbers = [1, 2, 3]; let moreNumbers = [...numbers, 4, 5]; console.log(moreNumbers); // Outputs: [1, 2, 3, 4, 5]
Rest Operator:
function sum(...args) { return args.reduce((total, num) => total + num, 0); } console.log(sum(1, 2, 3, 4)); // Outputs: 10
7. for...of Loop
The for...of loop is used to iterate over iterable objects like arrays.
Example:
let fruits = ["apple", "banana", "cherry"]; for (let fruit of fruits) { console.log(fruit); }
8. Promises
Promises represent asynchronous operations. They have three states: pending, resolved, and rejected.
Example:
let fetchData = new Promise((resolve, reject) => { let success = true; if (success) { resolve("Data loaded successfully!"); } else { reject("Error loading data."); } }); fetchData .then(response => console.log(response)) .catch(error => console.log(error));
9. Practical Examples
Example 1: Combining Template Literals and Arrow Functions
let greet = (name = "Guest") => `Hello, ${name}!`; console.log(greet("Alice")); // Outputs: Hello, Alice! console.log(greet()); // Outputs: Hello, Guest!
Example 2: Using Destructuring
let car = { brand: "Toyota", model: "Corolla", year: 2022 }; let { brand, model } = car; console.log(`Brand: ${brand}, Model: ${model}`);
Example 3: Spread Operator for Merging Arrays
let numbers1 = [1, 2, 3]; let numbers2 = [4, 5, 6]; let combined = [...numbers1, ...numbers2]; console.log(combined); // Outputs: [1, 2, 3, 4, 5, 6]
10. Practice Exercises
Task 1: Use Default Parameters
Write a function to calculate the total price, where the tax rate defaults to 10%.
Example Solution:
function calculateTotal(price, taxRate = 0.1) { return price + price * taxRate; } console.log(calculateTotal(100)); // Outputs: 110 console.log(calculateTotal(100, 0.2)); // Outputs: 120
Task 2: Use the Rest Operator
Write a function that calculates the average of any number of arguments.
Example Solution:
function average(...numbers) { let total = numbers.reduce((sum, num) => sum + num, 0); return total / numbers.length; } console.log(average(10, 20, 30)); // Outputs: 20
Task 3: Use Promises
Create a promise that simulates fetching data and resolves after 2 seconds.
Example Solution:
let fetchData = new Promise((resolve) => { setTimeout(() => resolve("Data fetched!"), 2000); }); fetchData.then(response => console.log(response));
11. Common Errors
-
Using
varInstead ofletorconst:var x = 10; var x = 20; // No error but overwrites the variable -
Forgetting to Use
returnin Arrow Functions:let add = (a, b) => a + b; // Correct let subtract = (a, b) => { a - b }; // Missing return, returns undefined -
Misusing Destructuring:
let { name, age } = undefined; // Error: Cannot destructure property