Preparing your workspace
Destructuring extracts values from objects and arrays, while spread and rest syntax provide concise ways to copy, combine, or collect values.
Destructuring allows you to take values directly from objects or arrays and assign them to variables. Spread syntax uses three dots to expand values into a new array, object, or function argument list. Rest syntax uses the same three dots to collect remaining values into an array or object. These features make modern JavaScript easier to read, especially when working with API data and function parameters. Spread creates shallow copies, not deep copies, which is important when nested objects are involved.
A React or API-based application often destructures properties from data objects and uses spread syntax when creating updated objects.
const student = {
name: 'Aman',
score: 90,
course: 'JavaScript'
};
const { name, score } = student;
const scores = [80, 85, 90];
const updatedScores = [...scores, 95];
console.log(name);
console.log(updatedScores);The code extracts the student's name and score and creates a new array containing the old scores plus 95.