/

Destructuring Objects and Arrays in JavaScript

Destructuring Objects and Arrays in JavaScript

Learn how to use the destructuring syntax to work with arrays and objects in JavaScript.

Destructuring in JavaScript allows you to extract values from objects and arrays and assign them to variables in a more concise way. This can make your code more readable and efficient.

Destructuring Objects

With object destructuring, you can extract specific properties from an object and assign their values to named variables. This can be especially useful when working with large objects or when you only need certain properties.

1
2
3
4
5
6
7
8
9
10
11
const person = {
firstName: 'Tom',
lastName: 'Cruise',
actor: true,
age: 54
};

const { firstName: name, age } = person;

console.log(name); // Tom
console.log(age); // 54

In the example above, the firstName property of the person object is assigned to the name variable, and the age property is assigned to the age variable. You can choose any variable name you want when destructuring.

Destructuring Arrays

Destructuring also works with arrays. You can extract specific values from an array and assign them to variables.

1
2
3
4
5
const a = [1, 2, 3, 4, 5];
const [first, second] = a;

console.log(first); // 1
console.log(second); // 2

In the example above, the values at index 0 and 1 of the array a are assigned to the first and second variables, respectively.

You can also skip elements in the array when destructuring:

1
2
3
4
5
const [first, second, , , fifth] = a;

console.log(first); // 1
console.log(second); // 2
console.log(fifth); // 5

In this example, the values at index 0, 1, and 4 are assigned to the first, second, and fifth variables, respectively. The empty commas indicate the skipped elements.

Destructuring objects and arrays can greatly simplify your code and make it more readable. It allows you to extract only the data you need and assign it to meaningful variable names.

tags: [“javascript”, “destructuring”, “objects”, “arrays”]