Beginner LevelJavaScript & TypeScript
What are rest parameters and the spread operator in JavaScript?
❓ Interview Prompt: Explain the three-dot syntax (...) for rest parameters in function definitions and spread syntax in array/object literals.
The ... syntax has two distinct uses based on context:
1. Rest Parameters (Function parameter definition):
Collects remaining function arguments into a true Array instance. Replaces the legacy arguments object.
•
Syntax:
function fn(a, b, ...rest) {}•
Must be the last parameter in the function signature.
2. Spread Operator (Array/Object literals & call sites):
Unpacks elements of an iterable (array/string) or properties of an object into individual elements/keys.
•
Shallow copies arrays and objects:
const copy = { ...original };•
Combines arrays:
const merged = [...arr1, ...arr2];Code Implementation Example
javascript
// Rest Parameter: collects arbitrary arguments into an array
function sum(...numbers) {
return numbers.reduce((total, n) => total + n, 0);
}
console.log(sum(1, 2, 3, 4)); // 10
// Spread Operator: expands array into function arguments
const nums = [5, 12, 8, 130, 44];
Math.max(...nums); // 130
// Object Spread: shallow merging
const base = { theme: 'dark', font: 'Inter' };
const override = { font: 'Roboto', showSidebar: true };
const config = { ...base, ...override }; // { theme: 'dark', font: 'Roboto', showSidebar: true }💡Rest parameters collecting arguments vs spread operator merging objects and expanding arrays.
🎯 Interview Key Takeaway
Rest collects multiple elements into an array; spread expands an array or object into individual elements.
#Spread#Rest Parameters#ES6#Beginner
Back to all JavaScript & TypeScript Questions→