InterviewHubPRO
Section Overview
Q422

Question 422 of 521

Part 7: Execution Context, Functional JS & V8 Engine (404 - 463)

81%
JavaScript Internals (521 Qs)•Part 7: Execution Context, Functional JS & V8 Engine (404 - 463)

What are the differences between spread operator and rest parameter

Rest parameter collects all remaining elements into an array. Whereas Spread operator allows iterables( arrays / objects / strings ) to be expanded into single arguments/elements. i.e, Rest parameter is opposite to the spread operator.

Practical Code Example

javascript
// Spread vs Rest:
// Rest (...args): Gathers multiple elements into an array in function parameters / destructuring:
function sum(...numbers) { return numbers.reduce((a, b) => a + b, 0); }

// Spread (...arr): Expands an iterable array into individual arguments / elements:
const arr1 = [1, 2];
const arr2 = [...arr1, 3, 4]; // [1, 2, 3, 4]