DEV Community

Aakash Srivastav
Aakash Srivastav

Posted on

Array Destructuring in Depth

In this post, our major focus will be on learning how to harness the power of destructuring to simplify our JavaScript programs.

What does the term Destructuring mean ?

You can think of it mentally as Decomposing a structure into individual parts .
The purpose of destructuring as a feature is to assign individual parts from some larger structure.

i) Let’s imagine , we’ve a function that returns us some user names.And I would grab the data and assigning it off into a variable , say awesomeTeachers.

function instructors(){
return ['Will','Kyle','Jonas'];
}
var awesomeTeachers= instructors();

Now , I want to get these three usernames into three different variables.
Let's follow the normal approach first :

Normally , I would be assigning off the individual element values into three different variables like this :

function instructors(){
return ['Will','Kyle','Jonas'];
}
var awesomeTeachers= instructors();

var teacherOne = awesomeTeachers[0];
var teacherTwo = awesomeTeachers[1];
var teacherThree = awesomeTeachers[2];

console.log(teacherOne );       // Will
console.log(teacherTwo );       // Kyle
console.log(teacherThree );     // Jonas

Now , let's use Destructuring approach:

function instructors(){
return ['Will','Kyle','Jonas'];
}

let [ teacherOne,
      teacherTwo,
      teacherThree
    ] = instructors();

That's it. We have reduces plenty of lines of code by this approach.

Now , let's handle the varieties of this example:

a) What will happen if we removed the third name from the array i,e

function instructors(){
return ['Will','Kyle'];
}

let [ teacherOne,
      teacherTwo,
      teacherThree
    ] = instructors();

Now , teacherThree will be undefined.
Remember , if our destructuring pattern indicates something that doesn’t exist, then it just gets assigned undefined .

b) I had an extra value but we didn’t account for it on the left-hand side i,e

function instructors(){
return ['Will','Kyle','Jonas','Andrew'];
}

let [ teacherOne,
      teacherTwo,
      teacherThree
    ] = instructors();

Nothing significant will happen ,last value i,e 'Andrew' just get ignored.

c) What if it was possible for one of these positions to come back as undefined ?

function instructors(){
return ['Will',,'Jonas',];
}

let [ teacherOne,
      teacherTwo,
      teacherThree
    ] = instructors();

In this case, value of teacherTwo would be undefined .
It would always be best to provide some sort of default.

function instructors(){
return ['Will',,'Jonas',];
}

let [ teacherOne,
      teacherTwo = 'teacher',
      teacherThree
    ] = instructors();

Note:

  • It’s important to understand that the default value expression only applied when there’s an undefined .
  • If I got null instead of undefined what the variable teacherTwo would be null not the default value provided.

d) What if our array had several other names in it and I couldn’t predict how many values it had in it? But I want all of them to have to be collected up into an array ?

We can use the gather or rest syntax.

function instructors(){
return ['Will','Kyle','Jonas','Wes','Andrew','Dylan','Maximilian'];
}

let [ teacherOne,
      teacherTwo,
      teacherThree,
      ...fourth
    ] = instructors();

e) Till now , we've been directly gathering the values in appropriate variables. But it might be the case that we’d actually like to have a reference to the whole structure as well.

Then we need to do this :

function instructors(){
return ['Will','Kyle','Jonas'];
}

let [ teacherOne,
      teacherTwo,
      teacherThree,
    ] = wholeArray = instructors();

Here , first wholeArray will get assigned the array and then that array is gonna get destructured by the given pattern.

ii) Declaration-assignment

We can also declare the variables first and then use destructuring pattern.Let's have a look:

function instructors(){
return ['Will','Kyle','Jonas'];
}

let wholeArray = instructors();

let [ teacherOne,
      teacherTwo,
      teacherThree
    ] = wholeArray ;

a) Assigning to objects:

If we’re can assign them to variables that already exist, we could also assign them to entirely other locations.Let's see :

function instructors(){
return ['Will','Kyle','Jonas'];
}

wholeArray = instructors();
let obj = { };

let [ obj.teacherOne,
      obj.teacherTwo,
      obj.teacherThree
    ] = wholeArray ;

b) Assigning to array:

In the same way as we did for objects, we can also assign them to any array position :

function instructors(){
return ['Will','Kyle','Jonas'];
}

wholeArray = instructors();
let arr= [ ];

let [ arr[0],
      arr[1],
      arr.[2]
    ] = wholeArray ;

iii) Comma Seperation

What if I didn't care about any name in the array ?
We can ignore them just by using comma . Let's see:
If I don't want our second item i,e 'Kyle' , we can just use comma at that place.

function instructors(){
return ['Will','Kyle','Jonas'];
}

wholeArray = instructors();

let [ teacherOne,
      ,
      teacherThree,
    ] = wholeArray ;

iv) Parameter Arrays

If we can do array destructurings on our assignment list, __we can also do them in parameter positioning .

function data([
  teacherOne,
  teacherTwo,
  teacherThree
]) {
    // ...
}

v) Providing Defaults:

function instructors(){
return null;
}

wholeArray = instructors();
let arr= [ ];

let [ teacherOne,
      teacherTwo,
      teacherThree,
    ] = wholeArray ;

In the above code , what would happen if our function instructors didn't returned any array or returned null ?
We’ll get a type error .

So , in order to fix this , we can provide a default empty array , so that if data comes back false from function , then it will just pick up the empty array .

function instructors(){
return null;
}
instructors();

let arr= [ ];

let [ teacherOne,
      teacherTwo,
      teacherThree,
    ] = instructors() || [ ];

The only motive of this was to save ourself from typeError.
teacherOne , teacherTwo and teacherThree are still undefined .

  • We can do the same thing in parameter too :
function data([
  teacherOne,
  teacherTwo,
  teacherThree
] = []) {
    // ...
}

vi) Nested Array Destructuring

Let's use destructuring for Nested Array.
In destructuring , if we have a position inside an array that is also an array, then we need to break that thing down again as a destructuring pattern.
Let's see-

function instructors(){
return ['Will',['Kyle','Kent'],'Jonas'];;
}
instructors();

let arr= [ ];

let [ teacherOne,
     [
      teacherTwo,
      teacherThree
     ],
      teacherFour
    ] = instructors() || [ ];

So at position two, instead of having the target be a variable, we want the target to be another destructuring pattern.

a) What if instead of getting subarray at position two , we got undefined ?

Again ,we’re gonna get type error .
So , just like we did earlier , we can provide empty array as default here too :

function instructors(){
return ['Will',['Kyle','Kent'],'Jonas'];;
}
instructors();

let arr= [ ];

let [ teacherOne,
     [
      teacherTwo,
      teacherThree
     ] = [ ],
      teacherFour
    ] = instructors() || [ ];

vii) Swaping Two variables

We can use destructuring assignment to swap the values of variables.

let firstName = 'Will';
let lastName = 'Sentance';

[ firstName , lastName ] = [ lastName , firstName ]

Conclusion

JavaScript is full of complex objects and arrays. Whether it’s the response from an HTTP request, or static data sets, being able to access the embedded content efficiently is important. Using destructuring assignment is a great way to do that. It not only handles multiple levels of nesting, but it allows for focused access and provides defaults in the case of undefined references.

Thank you or reading :)

If you have any question regarding this or anything I should add, correct or remove, feel free to comment, email or DM me. Thanks !!!

Top comments (4)

Collapse
 
ashishkumar profile image
Ashish Kumar

Great explanation... loved it!!

Collapse
 
aakashsr profile image
Aakash Srivastav

Thanks @ashish :)

Collapse
 
shubhamjaiswl profile image
Shubham Jaiswal

Clear My Doubts

Collapse
 
aakashsr profile image
Aakash Srivastav

Happy to help you @shubham :)