Skip to content

Rest and Spread Operators

Der Array Spread Operator “breitet” eine kommagetrennte Liste aus:

const array = [1, 2, 3, 4, 5];
console.log(array);
> Array(5) [1, 2, 3, 4, 5]
console.log(...array);
> 1 2 3 4 5
const names = ['Pedro', 'Axi', 'Bibs'];
function logNames(name1, name2, name3) {
console.log(name1);
console.log(name2);
console.log(name3);
}
// spreading arrays as arguments:
logNames(...names);
// spreading arrays into arrays:
// + substitute for concat!
const array2 = [1, 2, 3, ...names];
console.log(...array2);
// substitute for Array.from
const items = document.querySelectorAll('.item');
const arrayFromItems = Array.from(items);
const arrayFromSpread = [...items];

Gegenteil von Spread

// Funktion mit vielen Argumenten:
// Der Rest Operator packt Items in ein Array
function logNames2(...names) {
names.forEach(name => console.log(name));
}
logNames2('Bib', 'Axi', 'Pedro', 'George', 'Pye', 'Zack', 'Cloud');
// Array Rest and Destructuring
const scores = [100, 99, 98];
const [first, ...restOfScores] = scores;
console.log(scores);
console.log(first);
console.log(restOfScores);

Spreads an object properties into another object

const fruitBlender = {
blendKiwi: true,
blendMango: true,
}
const megaBlender = {
blendGuava: true,
...fruitBlender,
}
console.log(megaBlender);

While destructuring objects, pack remaining properties into a variable with the rest operator

const fruitBlender2 = {
blendKiwi: true,
blendMango: true,
blendGuava: true,
blendBanana: true,
blendPapaya: true,
blendOrange: true,
}
// const { blendKiwi, ...otherProps } = fruitBlender2;
// console.log(fruitBlender2);
// console.log(blendKiwi);
// console.log(otherProps);
const exArray = [1, 2, 3, 'blubb', 'whompst', 'purr'];
console.log(...exArray);
function lotsOfArgs(arg1, arg2, arg3, arg4, arg5, arg6) {
console.log(arg1, arg2, arg3, arg4, arg5, arg6);
}
lotsOfArgs(...exArray);
const ex2Array = ['black cat', 'white cat', 'orange cat'];
const conCatArray = [...exArray, ...ex2Array];
console.log(...conCatArray);
function moreArgs(...args) {
console.log(...args);
}
moreArgs(...conCatArray);
const [cat1, ...restOfCats] = ex2Array;
console.log(cat1);
console.log(...restOfCats);
const { blendKiwi, blendMango, ...fruitSalad } = fruitBlender2;
console.log(blendKiwi);
console.log(blendMango);
console.log(fruitSalad);
const obj1 = {
prop1: 'one',
prop2: 'two',
prop3: 'three',
};
const obj2 = {
...obj1,
prop4: 'four',
prop5: 'five',
prop6: 'six',
};
console.log(obj2);