|
| 1 | + |
| 2 | +// ES6 Rest Operator (...) |
| 3 | + |
| 4 | +// The rest operator collects multiple elements into a single array or object. |
| 5 | +// It looks exactly like the spread operator (...), but it works in the opposite direction. |
| 6 | +// Spread → expands items |
| 7 | +// Rest → collects items |
| 8 | + |
| 9 | + |
| 10 | +// Rest with Arrays (Function Arguments) |
| 11 | + |
| 12 | +// The rest parameter allows a function to accept any number of arguments as an array. |
| 13 | + |
| 14 | +function sum(...numbers) { |
| 15 | + return numbers.reduce((total, n) => total + n, 0); |
| 16 | +} |
| 17 | + |
| 18 | +console.log(sum(1, 2, 3)); // Output: 6 |
| 19 | +console.log(sum(5, 10, 15, 20)); // Output: 50 |
| 20 | + |
| 21 | +// Rest in Array Destructuring |
| 22 | + |
| 23 | +const fruits = ["apple", "banana", "mango", "orange", "grape"]; |
| 24 | + |
| 25 | +const [first, second, ...others] = fruits; |
| 26 | +console.log(first); // Output: apple |
| 27 | +console.log(second); // Output: banana |
| 28 | +console.log(others); // Output: ['mango', 'orange', 'grape'] |
| 29 | + |
| 30 | + |
| 31 | +// Rest with Objects |
| 32 | + |
| 33 | +const user = { |
| 34 | + name: "David", |
| 35 | + age: 80, |
| 36 | + country: "Kenya", |
| 37 | + profession: "Developer" |
| 38 | +}; |
| 39 | + |
| 40 | +const { name, ...details } = user; |
| 41 | +console.log(name); // Output: David |
| 42 | +console.log(details); // Output: { age: 80, country: 'Kenya', profession: 'Developer' } |
| 43 | + |
| 44 | +// Combining Spread & Rest |
| 45 | + |
| 46 | +// Spread expands → Rest collects |
| 47 | + |
| 48 | +const numbers = [10, 20, 30, 40, 50]; |
| 49 | + |
| 50 | +// Spread: Pass array elements individually |
| 51 | +const newNumbers = [...numbers, 60, 70]; |
| 52 | +console.log(newNumbers); // Output: [10, 20, 30, 40, 50, 60, 70] |
| 53 | + |
| 54 | +// Rest: Collect multiple elements into one variable |
| 55 | +const [firstNum, ...remaining] = newNumbers; |
| 56 | +console.log(firstNum); // Output: 10 |
| 57 | +console.log(remaining); // Output: [20, 30, 40, 50, 60, 70] |
| 58 | + |
| 59 | + |
| 60 | +// Real-life Example |
| 61 | + |
| 62 | +function introduce(firstName, lastName, ...hobbies) { |
| 63 | + console.log(`Name: ${firstName} ${lastName}`); |
| 64 | + console.log(`Hobbies: ${hobbies.join(", ")}`); |
| 65 | +} |
| 66 | + |
| 67 | +introduce("Macharia", "David", "Coding", "Reading", "Cycling"); |
| 68 | +// Output: |
| 69 | +// Name: Macharia David |
| 70 | +// Hobbies: Coding, Reading, Cycling |
| 71 | + |
| 72 | +// Summary |
| 73 | + |
| 74 | +// - Rest Operator collects multiple values into one array or object. |
| 75 | +// - Common uses: function parameters & destructuring. |
| 76 | +// - Syntax: (...variableName) |
| 77 | +// - Difference: |
| 78 | +// → Spread expands (breaks apart arrays/objects) |
| 79 | +// → Rest collects (gathers items into one variable) |
0 commit comments