Arrays · Lesson 22 of 45
Destructuring
Pull values out of arrays and objects in one line.
7 minutes3 games
Destructuring unpacks an array or object into separate variables in one line: by position for arrays, by name for objects.
JavaScript
const point = [3, 7]
const [x, y] = point
console.log(x, y)
const [first, ...rest] = ["gold", "silver", "bronze"]
console.log(first, rest)
const user = { name: "Nour", city: "Alex", age: 21 }
const { name, city } = user
console.log(name, city)
const { age: years, country = "Egypt" } = user
console.log(years, country)Step by step1 / 4
- ▶let a = 1
- 2let b = 2
- 3;[a, b] = [b, a]
- 4console.log(a, b)
Variables
| a | 1 |
Output
…
What's the output?
const { title, pages = 100 } = { title: "JS" }
console.log(title, pages)What will this code print?
Complete the code
Pull price and qty out of the object.
const order = { price: 50, qty: 3 } const price, qty = order
Exercise
Unpack the array into first and second and print their sum (30).
Expected output: 30
JavaScript
const pair = [12, 18]
Learn more from
Played 0 of 3 games
Sign in to save your progress and earn XP.