Command Palette

Search for a command to run...

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

Destructuring: position, skip, default, rest

The default only replaces undefined, so null stays null.

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?

Destructuring: position, skip, default, rest ES2015+

Console

(nothing was printed)

Expected console output

10 20
10 30
0
10 [ 20, 30 ]
1 undefined
null