ES6+ Modern JavaScript FeaturesLesson 6.1
ES6+ Destructuring, Spread, and Rest
array destructuring, object destructuring, nested destructuring, default values in destructuring, spread operator, rest parameters
ES6+ Destructuring, Spread, and Rest
ES6 (ECMAScript 2015) and later versions of JavaScript introduced features that make code more concise, readable, and powerful. In this lesson we cover three of the most impactful: destructuring, the spread operator, and rest parameters. These are used constantly in modern JavaScript and in frameworks like React and Vue.
Array Destructuring
const [first, second, third] = [10, 20, 30];
console.log(first); // 10
console.log(second); // 20
// Skip elements
const [,, last] = [1, 2, 3, 4];
console.log(last); // 3
// Default values
const [a = 0, b = 0] = [5];
console.log(a); // 5
console.log(b); // 0
// Swap variables
let x = 1, y = 2;
[x, y] = [y, x];
console.log(x, y); // 2 1Object Destructuring
const user = { name: 'Alice', age: 30, city: 'London' };
const { name, age } = user;
console.log(name); // 'Alice'
// Rename during destructuring
const { name: userName, city: location = 'Unknown' } = user;
console.log(userName); // 'Alice'
console.log(location); // 'London'
// In function parameters
function displayUser({ name, age }) {
console.log(`${name} is ${age} years old.`);
}
displayUser(user); // 'Alice is 30 years old.'The Spread Operator
const arr1 = [1, 2, 3];
const arr2 = [4, 5, 6];
const combined = [...arr1, ...arr2];
console.log(combined); // [1, 2, 3, 4, 5, 6]
// Copy an array
const original = [1, 2, 3];
const copy = [...original];
copy.push(4);
console.log(original); // [1, 2, 3] โ unaffected
// Spread into function arguments
const numbers = [5, 2, 8, 1];
console.log(Math.max(...numbers)); // 8Rest Parameters
function sum(...numbers) {
return numbers.reduce((total, n) => total + n, 0);
}
console.log(sum(1, 2, 3)); // 6
console.log(sum(10, 20, 30, 40)); // 100
function logFirst(first, ...rest) {
console.log('First:', first);
console.log('Rest:', rest);
}
logFirst('a', 'b', 'c', 'd');
// First: a
// Rest: ['b', 'c', 'd']