Rest Parameters (…args) - Simple explanation:
What it does: Collects all remaining function arguments into an array
When to use Rest Parameters:
1. Unknown number of arguments
function greet(greeting, …names) {
return ${greeting} ${names.join(', ')};
}
greet(“Hello”, “John”, “Jane”, “Bob”); // “Hello John, Jane, Bob”
The Simple Rule:
Must be last parameter: ...rest always goes at the end
function wrong(a, ...rest, b) {} // ❌ Error!
function right(a, b, ...rest) {} // ✅ CorrectSpread Syntax (…arr) - Simple explanation:
What it does: Expands arrays/objects into individual elements
Common Spread Uses:
1. Function calls
javascript
Math.max(...[1, 5, 3]); // 5 (instead of Math.max(1, 5, 3))2. Array/Object copying
javascript
let arr = [1, 2, 3];
let copy = [...arr]; // shallow copy
let obj = {a: 1};
let objCopy = {...obj}; // shallow copy3. Merging arrays/objects
javascript
let merged = [...arr1, ...arr2];
let combined = {...obj1, ...obj2};Interview gotchas:
javascript
// Rest vs Spread - same syntax, different context
function func(...args) {} // REST (collecting)
func(...array); // SPREAD (expanding)
// Shallow copy only
let nested = [{a: 1}];
let copy = [...nested];
copy[0].a = 2; // Original also changes to 2!Bottom line: ... collects when receiving parameters, expands when passing arguments.
