JavaScript Spread Operator - Exercise 3
A modern browser's NodeList is iterable, so spread it into a new array to use array methods such as map() or filter(). The resulting array is a snapshot of the selected elements at that moment.
const items = [...document.querySelectorAll('li')];
console.log(Array.isArray(items));Spread the iterable at the call site so the function receives separate arguments, which the rest parameter then collects into an array.
function collect(...values) {
return values;
}
const result = collect(...new Set([1, 2, 3]));Object spread copies only an object's own enumerable properties. Properties coming from the prototype chain are not copied.
const base = { role: 'user' };
const member = Object.create(base);
member.name = 'Ava';
console.log({ ...member });Spread either a small object or an empty object depending on the condition.
const isAdmin = true;
const user = {
name: 'Ava',
...(isAdmin ? { role: 'admin' } : {})
};Create a shallow copy with spread first, then sort the copy so the original array stays unchanged.
const scores = [30, 10, 20];
const sortedScores = [...scores].sort((a, b) => a - b);Spread the defaults first and the user settings afterward so user-provided values override the defaults.
const defaults = { theme: 'light', pageSize: 10 };
const userSettings = { pageSize: 25 };
const finalSettings = { ...defaults, ...userSettings };The getter runs during the spread operation, and the resulting value is copied into the new object as a normal data property.
const source = {
get total() {
return 42;
}
};
const snapshot = { ...source };
console.log(snapshot.total);Spread the current top-level values into a new array or object. The result is a shallow snapshot, so nested references are still shared.
const state = { items: ['a', 'b'] };
const snapshot = { ...state };Very large arrays can create too many individual arguments, which may hurt performance or hit engine-specific argument limits.
const values = new Array(100000).fill(1);
// Math.max(...values) can be inefficient or fail in some environments.Create a new array literal and spread the existing values into it, along with any new values you want to add.
const items = ['a', 'b'];
const nextItems = [...items, 'c'];