Building Your Learning Module...
Getting things ready for you!
Find videos you like?
Save to resource drawer for future reference!
Three dots ... work like magic! They can spread items out (expand) or collect items together (gather). Same syntax, different uses!
Use ... to unpack (spread) array items or object properties
const arr = [1, 2, 3]; // Without spread console.log(arr); // [1, 2, 3] // With spread - unpacks items console.log(...arr); // 1 2 3
Merge multiple arrays into one
Make a copy of an array
Spread works with objects too - copy or merge properties
const person = { name: 'Alice', age: 25 };
const job = { title: 'Developer', company: 'Tech Corp' };
// Combine objects
const employee = { ...person, ...job };
console.log(employee);
// { name: 'Alice', age: 25, title: 'Developer', company: 'Tech Corp' }Copy and merge objects
Use ... to collect the rest of the items into an array
// Get first item, collect rest const [first, ...rest] = [1, 2, 3, 4, 5]; console.log(first); // 1 console.log(rest); // [2, 3, 4, 5]
...rest must always be the last item!Collect remaining array items
Collect remaining object properties
Use rest in function parameters to accept any number of arguments
function sum(...numbers) {
// numbers is an array of all arguments
let total = 0;
for (const num of numbers) {
total += num;
}
return total;
}
console.log(sum(1, 2, 3)); // 6
console.log(sum(1, 2, 3, 4, 5)); // 15Accept variable number of arguments
[...array] spreads items out
[...rest] gathers items into array
[...a, ...b] merges arrays
[first, ...rest] - rest is always last