30 Days of JAVASCRIPT #11/30

ES6+ Features part-2 (Destructuring, Spread and Rest Operators)

Destructuring

Destructuring is a way to extract values from arrays and objects and assign them to variables. It allows us to write less code and make our code more readable. Here is an example code that demonstrates the use of destructuring:

// Destructuring an array
const numbers = [1, 2, 3];
const [a, b, c] = numbers;
console.log(a); // Output: 1
console.log(b); // Output: 2
console.log(c); // Output: 3

// Destructuring an object
const person = { name: "John", age: 30 };
const { name, age } = person;
console.log(name); // Output: John
console.log(age); // Output: 30

In the above code, we use destructuring to extract values from an array and an object and assign them to variables. We then print the values of these variables to the console.

Spread Operator

The spread operator is denoted by three dots (...) and is used to spread the elements of an array or an object. It allows us to create a new array or object with the elements of the original array or object. Here is an example code that demonstrates the use of the spread operator:

// Spreading an array
const numbers1 = [1, 2, 3];
const numbers2 = [4, 5, 6];
const combinedNumbers = [...numbers1, ...numbers2];
console.log(combinedNumbers); // Output: [1, 2, 3, 4, 5, 6]

// Spreading an object
const person1 = { name: "John", age: 30 };
const person2 = { profession: "developer" };
const combinedPerson = { ...person1, ...person2 };
console.log(combinedPerson); // Output: { name: "John", age: 30, profession: "developer" }

In the above code, we use the spread operator to create a new array and a new object by combining the elements of two arrays and two objects, respectively.

Rest Operator

The rest operator is also denoted by three dots (...) and is used to represent an indefinite number of arguments as an array. It allows us to pass a variable number of arguments to a function. Here is an example code that demonstrates the use of the rest operator:

// Using rest operator in a function
function sum(...numbers) {
  return numbers.reduce((acc, curr) => acc + curr);
}
console.log(sum(1, 2, 3)); // Output: 6
console.log(sum(1, 2, 3, 4, 5)); // Output: 15

In the above code, we use the rest operator in a function to accept an indefinite number of arguments as an array. We then use thereduce()method to sum up the values of the array.In conclusion, destructuring, spread operator, and rest operator are powerful features in JavaScript that make working with arrays and objects easier and more efficient.