Intermediate 8 min

Destructuring, rest, and spread

Destructuring names selected values, while spread expands the contents of an array or object.

How it works

Read the pattern as a request for specific fields. In { title }, the property name and local variable are both title. For a replacement array, spread copies the entries out of the old array one by one; any object referenced by an entry can still be shared.

Walk through an example

const { title } = book reads the title field into a variable. [...values, 8] builds a new array with the original entries followed by 8.

What to watch for

Spread makes a shallow copy. If two arrays contain the same object, editing that object through one array affects what the other array sees.

Code example

const book = { title: 'Loops', level: 1 };
const { title } = book;
console.log(title);
console.log([...['a', 'b'], 'c']);

Check your understanding

How many items does a contain?

See the example and explanation
Worked example
Given const a = [1, 2]; const b = [...a, 3]
Answer 2

Spread copies each entry into the new array b. It leaves array a as it was.

Open practice problem
Next lessonMap, filter, and reduce