Destructuring & Spread
Definition
Destructuring is a JavaScript expression that makes it possible to unpack values from arrays, or properties from objects, into distinct variables. The spread syntax (...) allows an iterable (like an array or string) to be expanded in places where zero or more arguments are expected.
Explain Like I'm New
Imagine you get a big gift box (an object) with shoes, a shirt, and a hat. Instead of reaching into the box every single time you want one of them (`box.shoes`), you immediately take them out and put them on your bed (`const { shoes, hat } = box`). Now you can just use `shoes` directly. The spread operator is like taking everything out of one box and dumping it into a new, bigger box.
Real World Example
When receiving a large JSON response from a weather API, you probably only care about `temperature` and `humidity`. Destructuring lets you pull exactly those two pieces of data out immediately.
Common Use Cases
- •Extracting specific properties from function parameters (especially in React props)
- •Merging arrays or objects easily
- •Copying arrays or objects without modifying the original (shallow copy)
Interactive Example
Interview Questions
basic
- What is object destructuring?
- What does the spread operator (...) do?
intermediate
- How do you provide default values while destructuring?
- What is the difference between the rest parameter and the spread operator?
advanced
- How do you rename a variable while destructuring an object?
- Does the spread operator create a deep copy or a shallow copy?
trick
- Can you destructure nested objects?