Arrays
Destructuring Objects and Arrays in JavaScript
Learn how to use JavaScript destructuring to pull values out of objects and arrays into named variables, rename them, and skip array items you do not need.
8 minute lesson
Given an object, using the destructuring syntax you can extract just some values and put them into named variables:
const person = {
firstName: 'Tom',
lastName: 'Cruise',
actor: true,
age: 54 //made up
}
const { firstName: name, age } = person //name: Tom, age: 54
name and age contain the desired values.
The property is still called firstName; only the local variable is renamed. Add a default for a missing or undefined property:
const { role = 'member' } = person
A default does not replace null, because null is an explicit value. Destructuring null or undefined as an object throws, so validate an uncertain input before destructuring it.
The syntax also works on arrays:
const a = [1, 2, 3, 4, 5]
const [first, second] = a
This statement creates three variables from indexes 0, 1, and 4:
const [first, second, , , fifth] = a
Object destructuring follows property names; array destructuring follows position. That makes object results easier to evolve when callers should not depend on ordering.
Destructuring is especially useful at function boundaries:
function formatUser({ name, city = 'Unknown' }) {
return `${name} — ${city}`
}
But it does not clone nested data. The variables still refer to the same nested objects:
const user = { settings: { theme: 'dark' } }
const { settings } = user
settings.theme = 'light'
console.log(user.settings.theme) // light
Use the rest syntax to collect remaining properties without mutating the source: const { password, ...publicUser } = user. Remember this is a shallow copy too.
Try it: destructure an API response with a renamed ID, a default label, and a rest object. Then pass null and decide where validation should happen.
Lesson completed