DEV Community

Cover image for Arrays and Object Destructuring in Javascript
sarah
sarah

Posted on

Arrays and Object Destructuring in Javascript

I wrote this article for baddies like me who've used destructuring many times in javascript without really understanding its ins and outs. Destructuring is a cool feature that was introduced in ES6/ES2015, I believe to make our lives as developers easy.

As a JavaScript developer, you're probably familiar with the concept of objects and arrays. Objects and arrays are great for storing and manipulating data in JavaScript. However, sometimes you might find yourself in a situation where you only need a few specific values from an object or array. This is where destructuring comes in handy.

With destructuring, unpacking data from objects and arrays is done with ease, speed and efficiency. Let's dive in!

What is Destructuring Assignment

According to Mozilla, "The destructuring assignment syntax is a JavaScript expression that makes it possible to unpack values from arrays, or properties from objects, into distinct variables.

It is simply a way to extract specific data/values from objects or arrays and assign them to variables. It's a shorthand way of assigning values to variables and can help make code more readable and concise.

Benefit of Destructuring Assignment

  • Destructuring allows you to extract values from objects or arrays in a concise and readable way. Instead of accessing each property or element individually, you can extract all the values you need in a single statement.

  • With destructuring you get to extract specific values from objects or arrays, making your code more flexible. You can extract only the properties or elements you need, and ignore the rest.

  • Destructuring allows you to avoid repetition in your code. If you need to access the same property or element multiple times, you can extract it to a variable using destructuring, and then reference the variable instead of repeating the same code.

  • Destructuring is easy to use with functions particularly when working with functions that take objects or arrays as arguments. By destructuring the arguments, you can easily access the values you need without having to reference the original object or array.

  • Destructuring allows you to specify default values for properties or elements that may not exist or may be undefined. This can help prevent errors and simplify your code by avoiding the need for additional checks and conditionals.

Why Destructuring

Extracting Data from Arrays

Before ES6/ES2015 extracting data from an array was done this way:

let numbers = [‘1’,’2’,’3’,’4’,’5,’6’];
let secondNumber = numbers[1];
let lastNumber = numbers[numbers - 1] 

console.log(secondNumber); //2
console.log(lastNumber); //6

Enter fullscreen mode Exit fullscreen mode

This becomes repetitive if we have to do this over and over again.

With ES6/ES2015

let numbers = [‘1’,’2’,’3’,’4’,’5’,’6’];
let [firstNumber, secondNumber] = numbers; 

console.log(firstNumber); //1
console.log(secondNumber); //2
Enter fullscreen mode Exit fullscreen mode

It is more concise:

let [firstNumber, secondNumber] = [‘1’,’2’,’3’,’4’,’5’,’6’];

console.log(firstNumber); //1
console.log(secondNumber); //2
Enter fullscreen mode Exit fullscreen mode

Has the same result.

Variables can be declared before they get assigned

let firstNumber, secondNumber, thirdNumber;
let [firstNumber, secondNumber, thirdNumber] = [‘1’,’2’,’3’,’4’,’5’,’6’];

console.log(firstNumber);//’1’
console.log(secondNumber);//’2’
console.log(thirdNumber);//’3’
Enter fullscreen mode Exit fullscreen mode

In the code above you will notice that the variables are set from left to right so – the first variable gets the first item in the array, the second variable gets the second item in the array and so on…

Values can be skipped in arrays

It is possible to skip values in arrays using a comma (,). You can add a comma separator for each value you want to skip in the array. For example:

let [firstNumber,,thirdNumber,,] = [‘1’,’2’,’3’,’4’,’5’,’6’];

console.log(firstNumber);//’1’
console.log(thirdNumber);//’3’
Enter fullscreen mode Exit fullscreen mode

If you want to skip all the items in the array, do this –

let [,,,,,,] = [‘1’,’2’,’3’,’4’,’5’,’6’];
Enter fullscreen mode Exit fullscreen mode

Using the spread syntax to assign the rest of an array

The spread syntax allows an iterable object such as strings or arrays to be expanded into individual elements.

In some cases where we want to assign some of the array to variables and the rest of the items in an array to a particular variable, we would do this –

let [firstNumber, …anotherNumber] = [‘1’,’2’,’3’,’4’,’5’,’6’];

console.log(firstNumber);//’1’
console.log(anotherNumber);//[’2’,’3’,’4’,’5’,’6]
Enter fullscreen mode Exit fullscreen mode

With this you can unpack and assign the remaining part of an array to a variable.

Default Values in Arrays

Sometimes, the array that you're destructuring might not have a value that you're trying to extract. In such cases, you can provide a default value. For example, consider the following:

let [firstNumber = ‘4’,secondNumber = ‘2’] = [‘1’];


console.log(firstNumber);// ’1’
console.log(secondNumber);// ’2’
Enter fullscreen mode Exit fullscreen mode

secondNumber is not defined in the array so it falls back to 2

let numbers2 = [1, 2];

const [x, y, z = 3] = numbers2;

console.log(x); // Output: 1
console.log(y); // Output: 2
console.log(z); // Output: 3
Enter fullscreen mode Exit fullscreen mode

In this example, we're trying to extract three values from the numbers2 array, but it only has two elements. Instead of throwing an error, we can specify a default value for z using the (=) operator.

Swapping values using array destructuring assignment

We can also use array destructuring to swap variable values without needing a temporary variable:

let a = 1;
let b = 2;

[a, b] = [b, a];

console.log(a); // Output: 2
console.log(b); // Output: 1
Enter fullscreen mode Exit fullscreen mode

In this example, we're swapping the values of a and b without needing a temporary variable. We do this by creating a new array with the two values in the opposite order and then using array destructuring to assign the new values to the variables.

Array destructuring is particularly useful when working with arrays that have a fixed number of elements and where you only need to extract a subset of those elements.

Extracting Data from Objects

Before ES6/ES2015 extracting data from an object is done this way:

let person = { name: 'Sarah', age: 29, gender: 'female' };

let name = person.name;
let age = person.age;
let gender = person.gender;

console.log(name);// ‘Sarah’
console.log(age);// ‘29’
console.log(gender);// ‘female’

Enter fullscreen mode Exit fullscreen mode

Look at the example above and notice the repetition I explained earlier in the array example.

With ES6/ES2015 Object Destructuring

const person = { name: 'Sarah', age: 29, gender: 'female' };
const { name, age } = person;
Enter fullscreen mode Exit fullscreen mode

In the example above the name and age properties was extracted and assigned variables with the same name.
This will create two variables name and age with the values 'Sarah' and 29, respectively.

let { name: personName, age: personAge } = person;
Enter fullscreen mode Exit fullscreen mode

You can also use destructuring to assign the extracted values to variables with different names. This will create two variables personName and personAge with the values 'Sarah' and 29, respectively.

One thing to keep in mind is variables in the object on the left hand side should have the same name as a property key in the object person. If the names are different, we'll get undefined.

Values of an object can be assigned to a new variable instead of using the name of the property:

let person = { name: 'Sarah', age: 29, gender: 'female' };
let {name: foo, gender: bar} = person;

console.log(foo);//’Sarah’
console.log(bar);//’female’
Enter fullscreen mode Exit fullscreen mode

Default Values

Default values comes in handy in cases where a variable is undefined in an object it wants to extract data from.

let person = {name: ‘Sarah’, country: ‘Nigeria’, job: ‘Developer’};

let {name = ‘myName’, friend = ‘Sophie’} = person;

console.log(name);//’Sarah’
console.log(friend);//’Annie’
Enter fullscreen mode Exit fullscreen mode

We can also set default values when we assign values to a new variable:

let person = {name: ‘Sarah’, country: ‘Nigeria’, job: ‘Developer’};

let {name:foo = ‘myName’, friend: bar = ‘Sophie’} = person;

console.log(foo);// ‘Sarah’
console.log(bar);// ‘Sophie’
Enter fullscreen mode Exit fullscreen mode

Nested Destructuring

You can use destructuring to extract values from nested objects and arrays. For example, consider the following object:

let person = { name: 'Sarah', age: 29, address: { street: '12, Admiralty St', city: 'Lagos' } };

Enter fullscreen mode Exit fullscreen mode

To extract the street and city properties from the address object and assign them to variables with the same name, you can use the following syntax:

let { address: { street, city } } = person;

Enter fullscreen mode Exit fullscreen mode

This will create two variables street and city with the values '12 Admiralty St' and 'Lagos', respectively.

You can also use destructuring to extract values from nested arrays. For example, consider the following array:

let numbers = [[1, 2], [3, 4]];
Enter fullscreen mode Exit fullscreen mode

To extract the value 3 from the array and assign it to a variable, you can use the following syntax:

let [, [c]] = numbers;
Enter fullscreen mode Exit fullscreen mode

This will create one variable c with the value 3.

Destructuring is a powerful feature in JavaScript. It can make your code more concise and readable, and it's definitely worth learning if you haven't already.

By using nested destructuring, you can extract values from complex data structures with ease.

I hope this helps you! 🖤🖤🖤

Top comments (2)

Collapse
 
developermonty profile image
MONTY WILLIAMS

Very well written! de-structuring for me was one of the concepts that helped me understand the significance of higher level languages and the relevance of data structures in software development. To us we have organized data for useful purposes, account info, user data etc. but for a cpu there are just registers and memory addresses. I cant imagine trying to do something as simple as de-structuring with a char array in C, I'm sure you would have to allocate the memory and manually iterate through each index of the array and deal with the pointers. I really enjoy the way javascript allows you to think so abstract and creatively. I know a few low level developers who look at such concepts with contempt arguing that the old fashioned efficient way is the only way. I enjoyed the article and its funny but I remember a time when I didn't understand de-structuring at all, I'm happy to say that I'm at the pont where I think I got this!

Collapse
 
sarahadewale profile image
sarah

you are soooo right! I am glad you enjoyed it. I smiled all through reading this! Thank you so much and yes, you got this!