Destructuring Objects and Arrays in JavaScript
By Flavio Copes
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.
Destructuring is a syntax that extracts values from objects and arrays into named variables, in a single statement. Instead of writing one assignment per property, you describe the shape of the data and JavaScript pulls the values out for you.
Given an object, 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.
Notice the two forms. age creates a variable with the same name as the property. firstName: name renames it: the value of firstName ends up in a variable called name.
Setting default values
You can assign a default, used when the property is missing:
const { age, nationality = 'unknown' } = person
nationality //'unknown'
The default only kicks in when the value is undefined. If the property exists with any other value, even null, you get that value.
Destructuring arrays
The syntax also works on arrays. Instead of property names, positions matter:
const a = [1, 2, 3, 4, 5]
const [first, second] = a
You can skip items you don’t need by leaving empty slots. This statement creates 3 new variables by getting the items with index 0, 1, 4 from the array a:
const [first, second, , , fifth] = a
Destructuring function parameters
My favorite use is in function parameters. When a function receives an object, you can destructure it right in the signature:
const introduce = ({ firstName, age }) => {
console.log(firstName, age)
}
introduce(person) //Tom 54
The caller passes the whole object, and inside the function you work with plain variables. No person.firstName repetition.
What happens if the value is undefined?
Destructuring null or undefined throws:
const { title } = undefined
//TypeError: Cannot destructure property 'title' of 'undefined'
This bites when the object comes from a function that can return nothing, like a failed lookup. The fix is to fall back to an empty object:
const { title } = findBook(42) ?? {}
title //undefined, no error
Now a missing result gives you undefined variables instead of a crash, and you can handle that case explicitly.
Related posts about js: