Mastering Destructuring Assignment in JavaScript (ES6)

Kevin Diesenberg
2 min readJun 7, 2023

Destructuring assignment, introduced in ES6, is a JavaScript expression that allows us to extract data from arrays, objects, maps, and sets into their own variable. It allows us to extract properties from an object or items from an array, multiple at a time.

Destructuring Arrays

Consider the following example of array restructuring:

const colors = ['red', 'green', 'blue'];
const [firstColor, secondColor] = colors;

console.log(firstColor); // 'red'
console.log(secondColor); // 'green'

We can also skip items in the array:

const colors = ['red', 'green', 'blue'];
const [, , thirdColor] = colors;

console.log(thirdColor); // 'blue'

Destructuring Objects

Similar to array destructuring, object destructuring extracts properties from an object:

const user = {
name: 'John Doe',
age: 30,
};

const { name, age } = user;

console.log(name); // 'John Doe'
console.log(age); // 30

You can assign the properties to variables with different names:

const user = {
name: 'John Doe',
age: 30,
};

const { name: userName, age: userAge } = user;

console.log(userName); // 'John Doe'
console.log(userAge); // 30

Destructuring Function Parameters

One practical use of destructuring is in function parameters. This can be particularly useful when a function takes an object as a parameter:

function greet({ name, age }) {
return `Hello, ${name}! You are ${age} years old.`;
}

const user = {
name: 'John Doe',
age: 30,
};

console.log(greet(user)); // 'Hello, John Doe! You are 30 years old.'

Nested Destructuring

You can use destructuring on nested objects or arrays:

const user = {
name: 'John Doe',
age: 30,
address: {
city: 'New York',
country: 'USA',
},
};

const {
name,
address: { city, country }
} = user;

console.log(name); // 'John Doe'
console.log(city); // 'New York'
console.log(country);// 'USA'

Conclusion

Destructuring assignment in JavaScript provides a more concise and readable way to deal with arrays and objects. It can be a powerful tool in your coding arsenal, helping you write cleaner, more understandable code.

In the next article, we will delve into the rest/spread operators, another powerful ES6 feature. Stay tuned!

--

--

Kevin Diesenberg

Software Engineer | JavaScript | React | Ruby | Rails | SQL | Skydiver | Outdoor Enthusiast | Paramotor Pilot | Cyclist | Edible Mushroom Hunter