Destructuring & Spread
Destructuring & Spread is a core JavaScript concept covering destructuring & Spread: Destructuring assignment is a special syntax This topic is essential for academic learning, board exam preparation, and developing optimized real-world code.
1. Destructuring
Destructuring assignment is a special syntax that allows us to "unpack" arrays or objects into a bunch of variables.
Array Destructuring
const fruits = ["Banana", "Orange", "Apple"];
let [fruit1, fruit2] = fruits;
console.log(fruit1); // Banana
console.log(fruit2); // Orange
Object Destructuring
const person = {
firstName: "John",
lastName: "Doe",
age: 50
};
let {firstName, lastName} = person;
console.log(firstName); // John
2. Spread Operator (...)
The spread operator expands an iterable (like an array) into more elements.
Combining Arrays
const q1 = ["Jan", "Feb", "Mar"];
const q2 = ["Apr", "May", "Jun"];
const year = [...q1, ...q2];
Copying Objects
const person = { name: "John" };
const updatedPerson = { ...person, age: 30 };
Rest Parameter
The same ... syntax is used for Rest Parameters in functions, which collects all remaining arguments into an array: function sum(...args).