Destructuring, Spread & Rest: Interview Essentials
JS جاوااسکریپت

Destructuring, Spread & Rest: Interview Essentials

Unpack objects and arrays, clone data, and merge defaults — patterns that show up in every JS interview.

BugCast Admin··۵ دقیقه مطالعه

Destructuring, spread, and rest syntax make JavaScript data manipulation concise. Interviewers use them to test whether you understand immutability and default values.

Common Interview Questions

Q: How do you swap two variables without a temp variable?

Answer: Array destructuring assignment swaps values in one expression. It works because the right-hand side is evaluated first into a temporary array.


let a = 1, b = 2;
[a, b] = [b, a];

Q: What is the difference between rest and spread?

Answer: Spread expands an iterable into individual elements (...arr in literals or function calls). Rest collects remaining elements into an array or object (...rest in parameters or destructuring). Same syntax, opposite direction.

Q: How do default values interact with destructuring?

Answer: Defaults apply when the property is undefined, not when it is null or missing with no default. For arrays, defaults apply to undefined slots.


const { role = "guest", id = 0 } = { role: undefined };
// role is undefined, id is 0

Q: Shallow clone an object and override one field

Answer: Object spread creates a shallow copy — nested objects are still shared references. For deep updates, combine spread at each nested level or use structured cloning.


const next = { ...user, name: "Updated" };

Key Points for Interviews

  • Spread copies enumerable own properties shallowly

  • Rest must be the last element in destructuring patterns

  • Renaming: { name: userName } pulls name into userName

  • Nested destructuring works but can hurt readability

  • Common in React props, Redux reducers, and API mapping

#destructuring#spread#interview

مطالب مرتبط