ECMAScript question detail
Object rest and spread operators
ES2015 or ES6 introduced both rest parameters and spread operators to convert arguments to array and vice versa using three-dot(...) notation.
- Rest parameters can be used to convert function arguments to an array
function myfunc(p1, p2, ...p3) {
console.log(p1, p2, p3); // 1, 2, [3, 4, 5, 6]
}
myfunc(1, 2, 3, 4, 5, 6);
- The spread operator works in the opposite way by converting an array into separate arguments in order to pass to a function
const myArray = [10, 5, 25, -100, 200, -200];
console.log( Math.max(...myArray) ); // 200
ES2018 enables this rest/spread behavior for objects as well.
- You can pass object to a function
function myfunc1({ a, ...x }) {
console.log(a, x); // 1, { b: 2, c: 3, d:4 }
}
myfunc1({
a: 1,
b: 2,
c: 3,
d: 4
});
- The spread operator can be used within other objects
const myObject = { a: 1, b: 2, c: 3, d:4 };
const myNewObject = { ...myObject, e: 5 }; // { a: 1, b: 2, c: 3, d: 4, e: 5 }