DEV Community

Edmund 🚀
Edmund 🚀

Posted on • Originally published at theninja.codes on

Advanced techniques in destructuring (How to destructure arrays and objects - Part 3)

There are advanced techniques used in destructuring to help us write even cleaner code, from the last two articles, we discussed how destructuring works in arrays and objects.

In this article we'll be looking at ways to take destructuring in JavaScript a step further If any of the techniques seem strange to you, I'd suggest you read the last two parts 👌, let's dive in shall we?


a man diving into water

How to destructure function parameters

This technique is very popular, especially when working with objects being passed as arguments to a function.

Destructuring function parameters in objects

Say we had an object man with some properties:

const man = {
  name: 'Johny',
  age: 50,
  hairColor: 'black'
}

If we needed to get specific details about 'man' when the object is passed as an argument:

function getName({name}){
  return name;
}

getName(man); // 'Johny'
getName({name: 'Sandy', age:24}); // 'Sandy'

Note: the name of the key you want to destructure must match the variable name you use, to change the name, set an alias (see part 2).

Doing the same for arrays

It's possible to destructure arrays passed to functions as arguments too:

const friends= ['Mike', 'Bill', 'Jill', 'Max'];
function getBestFriend ([friendOne]){
return friendOne;
}
getBestFriend(friends); // 'Mike'

so we're taking the first friend from the array of friends and returning it as the best friend.

It's also possible to use the rest parameter ... to assign the remaining elements to another variable.

Nested destructuring

It's possible to get properties that are several levels deep in an object or value in an array:

Nested object destructuring

If we need to get a nested property in an object, this is how it would be:

const user = {
  name: 'Naira Marley',
  age: 12,
  socialMedia: {
    twitter: '@officialnairam1'
  }
}

function getTwitter({ socialMedia:{twitter} }){
  return twitter;
}

getTwitter(user); // '@officialnairam1'

Nested array destructuring

It is also possible to get values from nested arrays

const colours = ['#000000', [255, 0, 0] , '#ffffff'];

function getRed([hex_black, [rgb_red, ,], hex_white]){
  return rgb_red;
}

getRed(colours);

Notice how i skipped the other rgb values?

Declaring variables before use

It's possible to declare variables before use, however, there is one gotcha with using this technique when destructuring objects, lucky for us, there's a workaround which we'll see soon.

Declaring variables before use in arrays

let white, black, green, yellow;

[white, black, green, yellow] = ['#ffffff', '#000000','#1ed947', '#fff829'];

console.log(green); // '#1ed947'

You are not permitted to copYou can also assign default values:

let white, black, green;
let yellow = 'yellow';
[white, black, green] = ['#ffffff', '#000000','#1ed947', '#fff829'];

console.log(yellow); // 'yellow'

Declaring variables before use in objects

let firstName = 'Post';
let lastName = 'Malone';
let country = 'U.S.A';

let firstName, lastName, country;

let user = {
  firstName: 'Zlatan',
  lastName: 'Ibile',
  country: 'Nigeria'
};

({ firstName, lastName, country } = user);

console.log(firstName); // 'Zlatan'

Notice how we used a pair of enclosing parentheses ()? that's because if we didn't, JavaScript will see that line as a block expression and code blocks do not appear on the left hand side of an assignment. An error would've been thrown.

Mixed destructuring

You thought that was all? nah, not even close, we can even go further to destructure arrays nested in objects and vice versa. Take a look at this object:

const user = {
  name: 'Janet',
  age: 23,
  sports: ['basketball', 'hockey', 'soccer']
}

const {name, sports: [firstSport, , lastSport]} = user;

console.log(firstSport); //basketball

To read further on destructuring, check out this page on the Mozilla Developer Network.

Top comments (3)

Collapse
 
fly profile image
joon

Had no idea that mixed destructuring was possible, thank you for the post - my future code probably just got much shorter

Collapse
 
x8er profile image
Maxim

We using () because variables were declared before use?

Collapse
 
26th_edmund profile image
Edmund 🚀

Not really, we use the brackets because a pair of {} standing alone is seen as a an expression, a code block, and code blocks do not appear on the Left side of an assignment, so we have to wrap it in () to convert to a statement. If it were in arrays it would be fine to do it without the parentheses.