JavaScript Spread Operator - Exercise 2
Place the spread array at the exact position where you want its elements inserted inside a new array literal.
const middle = ['b', 'c'];
const letters = ['a', ...middle, 'd'];
console.log(letters);Start a new array with the new item, then spread the existing array after it.
const items = ['b', 'c'];
const updated = ['a', ...items];Spread the original object into a new object and then provide the property you want to override.
const user = { name: 'Ava', active: false };
const updatedUser = { ...user, active: true };When you spread null or undefined into an object literal, no properties are copied, so the expression simply contributes nothing.
const settings = { theme: 'light', ...null };
console.log(settings);Strings are iterable, so spreading one into an array produces one element for each Unicode code point. This is convenient for simple character processing, although complex grapheme clusters may contain multiple code points.
const letters = [...'JavaScript'];
console.log(letters);Spread an iterable such as an array at the call site so its values become individual function arguments.
const values = [3, 8, 2];
console.log(Math.max(...values));Spread only copies the top-level references, so nested objects and arrays are still shared between the original and the copy.
const original = { profile: { name: 'Ava' } };
const clone = { ...original };
clone.profile.name = 'Liam';
console.log(original.profile.name);Spread both configuration objects into a new object. If the same key appears more than once, the later value wins.
const defaults = { theme: 'light', pageSize: 10 };
const userSettings = { pageSize: 20 };
const config = { ...defaults, ...userSettings };The last property assigned for that key wins, whether it comes from a later spread source or a later explicit property.
const result = { ...{ role: 'user' }, ...{ role: 'admin' } };
console.log(result.role);You can spread the array into a new array first and pass that iterable into Set, which is useful when you want a fresh iterable snapshot before duplicates are removed.
const values = [1, 2, 2, 3];
const uniqueValues = new Set([...values]);