By the end of this lesson, you will understand how to use destructuring, spread, and rest in JavaScript.
Destructuring is a powerful feature that lets you unpack values from arrays or properties from objects into distinct variables. For instance, consider an object representing a car:
const car = { make: 'Toyota', model: 'Camry', year: 2020 };
Using destructuring, you can easily get the values:
const { make, model } = car;
Now, make is ‘Toyota’ and model is ‘Camry’. This simplification improves your code quality.
The spread operator (...) allows you to expand elements of an iterable like an array or object. For example, if you have two arrays:
const nums1 = [1, 2, 3];
const nums2 = [4, 5, 6];
You can effectively combine them into one:
const numsCombined = [...nums1, ...nums2];
This results in [1, 2, 3, 4, 5, 6].
The rest parameter syntax (...) allows you to represent an indefinite number of arguments as an array. Here is an example:
function add(...numbers) {
return numbers.reduce((sum, num) => sum + num, 0);
}
This add function can accept any number of arguments and will return their sum.
File: demo.js
const person = { name: 'Alice', age: 25 };
const { name, age } = person;
console.log(name, age); // Alice 25
const nums = [1, 2, 3, 4];
const maxNumber = Math.max(...nums);
console.log(maxNumber); // 4
function collectData(...data) {
return data;
}
console.log(collectData(1, 2, 3)); // [1, 2, 3]
Expected Output:
Alice 25
4
[1, 2, 3]
In the code example, we first destructure the person object to retrieve name and age. Then, we utilize the spread operator to find the maximum number in the nums array. Finally, the collectData function gathers all passed arguments into an array.
Create a function that takes an object with firstName, lastName, and age properties. Use destructuring to print these values. As a bonus: Add a rest parameter to accept any hobbies as additional arguments and log them.
function displayUser({ firstName, lastName, age }, ...hobbies) {
console.log(firstName, lastName, age);
console.log('Hobbies:', hobbies);
}
const user = { firstName: 'Bob', lastName: 'Smith', age: 30 };
displayUser(user, 'Reading', 'Gaming', 'Traveling');