Rest Operator
Takes multiple things and packs it into a single array
function convertCurrency(rate, ...amounts) {
console.log(rate, amounts); // 1.5 [10, 20, 30]
}
convertCurrency(1.5, 10, 20, 30);
Can be used while destructuring into an array
const team = ["John", "Kait", "Lux", "Sheena", "Kelly"];
const [captain, assistant, ...players] = team;
console.log(captain, assistant, players);
Spread Operator
(3 dots in-front of an array or any iterable) Takes every single item from an iterable (that can loop over with for-of loop) and spread it into a new array
const featured = ["Deep Dish", "Pepperoni", "Hawaiian"];
const specialty = ["Meatzza", "Spicy Mama", "Margherita"];
const pizzas = [...featured, "veg", ...specialty];
Using above example, creating a new array fridayPizzas
const fridayPizzas = [...pizzas];
pizzas != fridayPizzas (shallow copy)
Spread string
const name = "john";
console.log([...name]); // ["j", "o", "h", "n"]
Remove an object from an array of objects
const comments = [
{ id: 209384, text: "I love your dog!" },
{ id: 523423, text: "Cuuute! 🐐" },
{ id: 632429, text: "You are so dumb" },
{ id: 192834, text: "Nice work on this wes!" }
];
const id = 632429;
const commentIndex = comments.findIndex(comment => comment.id === id);
const newComments = [
...comments.slice(0, commentIndex),
...comments.slice(commentIndex + 1)
];
console.log(newComments);
Spreading into a function
const inventors = ["Einstein", "Newton", "Galileo"];
const newInventors = ["Musk", "Jobs"];
inventors.push(...newInventors); // and not inventors.push(newInventors);
console.log(inventors);
One more example
const name = ["John", "Doe"];
function sayHi(first, last) {
alert(`Hey there ${first} ${last}`);
}
sayHi(...name);