Command Palette

Search for a command to run...

Hectal
Back to the lesson: Topic 5.8 — Destructuring and Spread with Arrays
JavaScript · Example 3 of 3 ES2015+

Spread: copy, merge, unpack

Pushing to copy didn't touch a. sum(...merged) spreads the array into arguments, and the rest parameter ...nums collects them back into an array.

Array destructuring unpacks items into variables by position (const [a, b] = arr), with skipping, defaults and a ...rest to collect the remainder; spread (...arr) does the opposite, unpacking an array into a new array or a function call, which is how you copy and merge arrays.

Change the code and press Run (Ctrl+Enter). Predict what will happen first, then break it on purpose and read what changes. Your edits are saved and match the lesson page.

Ready for more? This phase has 6 hands-on exercises with automatic checks.

Practice questions

Write the code in the editor, run it, then open the model answer to compare.

01

Given const scores = [88, 72, 95, 60];, put the first score in top and the rest in others, and print both.

02

Write addToFront(arr, item) that returns a new array with item first, without changing arr.

03

Use destructuring to get the hours and minutes as numbers from the string "09:45".

Explain it without notes

01

How does array destructuring work, and what happens to missing items?

02

How do you swap two variables in JavaScript without a temporary variable?

03

What is the difference between rest and spread?

04

How do you merge two arrays and remove duplicates?

Spread: copy, merge, unpack ES2015+

Console

(nothing was printed)

Expected console output

[ 1, 2, 3, 4 ] [ 0, 1, 2, 2.5, 3, 4, 5 ]
[ 1, 2 ] [ 1, 2, 99 ]
4
[ 'h', 'e', 'y' ]
[ 1, 2, 3 ]
10