ES6+ Destructuring & Spread
ES6 (ECMAScript 2015) introduced syntax patterns that significantly reduce boilerplate code. Destructuring and the Spread/Rest operators are key features.
1 Destructuring and Spread (...) Operator
These modern patterns simplify variable assignments:
- Destructuring: Extract values from objects or arrays directly into variables in a single line.
- Spread Operator (`...`): Expands elements of an array or properties of an object. This is highly useful for creating safe copies of objects/arrays without modifying the originals.
- Rest Parameter (`...`): Bundles multiple function parameters into a single array block.
2 ES6 Patterns Code
Let's run a program executing object destructuring, array destructuring, and object copies using spread:
JavaScript — ES6 Patterns
▶ Run Code
// 1. Destructuring
const user = { username: "nayak", email: "nayak@codes.com", role: "Admin" };
const { username, role } = user;
console.log(`User: ${username}, Role: ${role}`);
const coordinates = [10.5, 20.8];
const [x, y] = coordinates;
console.log(`X: ${x}, Y: ${y}`);
// 2. Spread Operator on Object copying
const baseSettings = { theme: "dark", notifications: true };
const userSettings = { ...baseSettings, notifications: false }; // Safe copy with override
console.log("User settings: ", userSettings);
console.log("Base settings (untouched): ", baseSettings);
3 Code Challenge
Challenge: Write a function called `sumAll` that uses rest parameters (`...args`) to sum any number of arguments passed to it. Test it with 3 arguments, then 6 arguments, and print the outputs.