Command Palette

Search for a command to run...

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

Swap, return several values, split a string

Click Swap: the same one-line swap runs on each click.

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?

Swap, return several values, split a string ES2015+

Preview

Press Run to see the page.

Console

Nothing logged yet.

Expected console output

2 1
1 9
2024 01 15