JavaScript Spread Operator - Exercise 1
Array spread expands an iterable array into individual values at the location where the three dots appear. It is useful for building another array or passing elements to a function without changing the original array.
const values = [1, 2, 3];
console.log(...values);
Put the existing array after ... inside a new array literal. This creates a shallow copy with a different outer array, so adding an element to the copy does not add it to the original.
const original = [1, 2];
const copy = [...original];
Put both arrays in a new array literal using spread syntax.
const first = [1, 2];
const second = [3, 4];
const combined = [...first, ...second];
No. It creates a shallow copy, so nested objects are still shared.
const source = [{ active: true }];
const copy = [...source];
Create a new array by spreading the existing items and placing the new value after them. This immutable update leaves the source array unchanged, which is useful when state should be replaced rather than mutated.
const next = [...items, 'new item'];
It copies an object's enumerable own properties into a new object.
const user = { name: 'Mia' };
const updated = { ...user, active: true };
A later property with the same key overwrites the earlier value.
const result = { ...{ role: 'user' }, role: 'admin' };
Spread an array in the function call so its elements become separate positional arguments. This is helpful with APIs such as Math.max() that do not accept an array directly.
const numbers = [4, 7];
Math.max(...numbers);
Array spread consumes iterable values, including arrays, strings, and sets. Each value produced by the iterable becomes an element in the new array; ordinary non-iterable objects cannot be spread into an array.
const letters = [...'cat'];
Spread expands an existing iterable or object into a new expression, while rest collects remaining values into an array or object. The same three-dot syntax has opposite roles depending on whether it appears in a declaration or a use site.
const [first, ...remaining] = [1, 2, 3];