Spread & Rest

The Spread Operator

Example

... expands an array or object into its elements:

const frontend = ["HTML", "CSS"];
const all = [...frontend, "JS", "SQL"];
console.log(all);
console.log(Math.max(...[4, 19, 7]));

const base = { theme: "light", lang: "en" };
const settings = { ...base, theme: "dark" };   // later keys win
console.log(settings);

Output

[ 'HTML', 'CSS', 'JS', 'SQL' ]
19
{ theme: 'dark', lang: 'en' }

Rest vs Spread

The same ... syntax means opposite things: rest collects many values into one (in parameters and destructuring), spread expands one into many (in calls and literals).

Example

const { password, ...publicUser } = { name: "Asha", email: "[email protected]", password: "secret" };
console.log(publicUser);   // rest: everything except password

Output

{ name: 'Asha', email: '[email protected]' }