JavaScript ES6: Comprehensive Guide
ES6 (ECMAScript 2015) introduced significant updates to JavaScript, making it more modern, concise, and powerful. This guide will teach you ES6 features with code examples, explanations, multiple-choice questions, and exercises.
Key Features of ES6
- Block-Scoped Declarations: let and const
- Arrow Functions
- Template Literals
- Destructuring
- Default Parameters
- Spread and Rest Operators
- Modules (import/export)
- Classes
- Promises and Async/Await
- Iterators and Generators
1. let and const
- let: Block-scoped, reassignable.
- const: Block-scoped, not reassignable.
Example:
let x = 10;
x = 20; // Allowed
const y = 30;
// y = 40; // Error: Assignment to constant variable
Why Use: Avoids issues with var hoisting and scope.
2. Arrow Functions
Arrow functions provide a shorter syntax for function expressions and do not bind their own this.
Example:
const add = (a, b) => a + b;
console.log(add(5, 3)); // Output: 8
3. Template Literals
Template literals allow embedding variables and expressions within strings.
Example:
const name = “Alice”;
console.log(`Hello, ${name}!`); // Output: Hello, Alice!
4. Destructuring
Destructuring allows unpacking values from arrays or properties from objects.
Array Destructuring:
const [a, b] = [1, 2];
console.log(a, b); // Output: 1 2
Object Destructuring:
const user = { name: “Alice”, age: 25 };
const { name, age } = user;
console.log(name, age); // Output: Alice 25
5. Default Parameters
Set default values for function parameters.
Example:
const greet = (name = “Guest”) => `Hello, ${name}!`;
console.log(greet()); // Output: Hello, Guest!
console.log(greet(“Alice”)); // Output: Hello, Alice!
6. Spread and Rest Operators
- Spread (…): Expands arrays or objects.
- Rest (…): Collects multiple arguments into an array.
Example:
// Spread
const arr1 = [1, 2, 3];
const arr2 = […arr1, 4, 5];
console.log(arr2); // Output: [1, 2, 3, 4, 5]
// Rest
const sum = (…nums) => nums.reduce((a, b) => a + b);
console.log(sum(1, 2, 3, 4)); // Output: 10
7. Modules
Use import and export for modular code.
Example:
Export:
// file: math.js
export const add = (a, b) => a + b;
export const subtract = (a, b) => a – b;
Import:
// file: main.js
import { add, subtract } from ‘./math.js’;
console.log(add(5, 3)); // Output: 8
8. Classes
ES6 introduced classes for object-oriented programming.
Example:
class Person {
constructor(name, age) {
this.name = name;
this.age = age;
}
greet() {
return `Hello, my name is ${this.name} and I am ${this.age} years old.`;
}
}
const alice = new Person(“Alice”, 25);
console.log(alice.greet());
// Output: Hello, my name is Alice and I am 25 years old.
9. Promises
Promises simplify asynchronous programming.
Example:
const fetchData = () => {
return new Promise((resolve, reject) => {
setTimeout(() => resolve(“Data fetched”), 1000);
});
};
fetchData().then((data) => console.log(data));
// Output: Data fetched
10. Async/Await
Async/await is built on Promises and provides cleaner syntax for handling asynchronous operations.
Example:
const fetchData = async () => {
const data = await new Promise((resolve) => setTimeout(() => resolve(“Data fetched”), 1000));
console.log(data);
};
fetchData();
// Output: Data fetched
Exercises
Exercise 1: Convert Function to Arrow Function
Rewrite the following as an arrow function:
function multiply(a, b) {
return a * b;
}
Solution:
const multiply = (a, b) => a * b;
Exercise 2: Destructure an Object
Given the following object, extract name and age:
const user = { name: “Bob”, age: 30, country: “USA” };
Solution:
const { name, age } = user;
console.log(name, age); // Output: Bob 30
Exercise 3: Write a Class
Create a Car class with properties make, model, and year, and a method getDetails.
Solution:
class Car {
constructor(make, model, year) {
this.make = make;
this.model = model;
this.year = year;
}
getDetails() {
return `${this.year} ${this.make} ${this.model}`;
}
}
const car = new Car(“Toyota”, “Corolla”, 2022);
console.log(car.getDetails());
// Output: 2022 Toyota Corolla
Multiple-Choice Questions
Question 1:
What is the output of the following code?
const arr = [1, 2, 3];
const [x, y] = arr;
console.log(x, y);
- 1, 2
- undefined, undefined
- [1, 2], undefined
- Error
Answer: 1. 1, 2
Question 2:
What does the … operator do in the following example?
const nums = [1, 2, 3];
const newNums = […nums, 4];
- Copies nums into newNums.
- Combines arrays.
- Adds numbers together.
- Destructures nums.
Answer: 1. Copies nums into newNums.
Question 3:
What will the following code output?
const greet = (name = “Guest”) => `Hello, ${name}!`;
console.log(greet());
- Error
- Hello, !
- Hello, Guest!
- undefined
Answer: 3. Hello, Guest!
Best Practices
- Use let and const: Replace var with let or const for better scoping.
- Prefer Arrow Functions: Use arrow functions for concise syntax, except where this binding is required.
- Use Default Parameters: Simplify function definitions with default values.
- Leverage Modules: Split your code into reusable modules using import and export.
- Handle Promises Properly: Use async/await for cleaner asynchronous code.