ARRAY DESTRUCTURING
If you love writing clean and readable code like I do, then you will find this article really helpful. The Destructuring syntax added to the 2015 Edition of the ECMAScript language specification makes it easier to assign values to variables by either creating, extracting or breaking down complex arrays and objects into meaningful, simpler parts.
The destructuring syntax can be used on both Array and Object in JavaScript.
In this article, we will be focusing on Array Destructuring. If you are not already familiar with Object Destructuring, you can check out my previous article on Object Destructuring In JavaScript
Table of Contents
In this article, we will be looking at:
An overview of destructuring.
Introduction to JavaScript array destructuring.
Practical applications of array destructuring.
Final notes
References
An Overview of Destructuring
Simply put, Destructuring as it relates to JavaScript is a feature that allows us to unpack values from arrays and objects to save into variables. With the inception of Destructuring, accessing array elements and object properties became easier and less complicated.
Introduction to JavaScript Array Destructuring
Array Destructuring helps you create new variables from array properties. In the example below, instead of accessing houseType
using the index of array elements, starting from 0
as was the case pre ES6, we can access them by extracting the array elements into new variables and assigning them to the corresponding elements in the array that share the same index with them. Take a look at the code snippet below:
//What was obtainable pre ES6
const houseType= [
"Bungalow",
"Duplex",
"Mansion",
"Penthouse"
]
console.log(houseType[0], houseType[1], houseType[2], houseType[3]);
See how we repeatedly had to use houseType
with the element's index number to access them individually? Pretty much stressful and repetitive right? Recalled I mentioned that this article would benefit you if you love writing, simple, clean and readable code using destructuring and in this case Array Destructuring?
Now lets refactor our code block above using Array Destructuring:
//What is obtainable now- post ES6
const houseType= [
"Bungalow",
"Duplex",
"Mansion",
"Penthouse"
]
const [Bungalow, Duplex, Mansion, Penthouse] = houseType;
console.log(Bungalow, Duplex, Mansion, Penthouse);
From our code block above, we successfully destructured our houseType
array and assignedBungalow
, Duplex
, Mansion
and Penthouse
to the corresponding elements that share the same index with them. Notice that each variable is mapped to the corresponding item at the same index on the houseType
array.
Practical applications of Array Destructuring
Default Values
We can use array destructuring to assign default values to excess items in an array or items not included in our array literal. Unless we specify default values to them, JavaScript will assign each item(s) a default value of undefined
. The code below explains it further:
const houseType= [
"Bungalow",
"Duplex",
"Mansion
]
const [ Bungalow, Duplex, Mansion, Penthouse] = houseType;
console.log(Penthouse);
//Output
Undefined
Recalled we stated earlier that excess items in a destructured array, if not properly defined will be rendered undefined
by JavaScript? See that playout when we console.log(Penthouse)
which returned a value of undefined
.
Note however, that unassigned values and array elements not assigned to variable names are completely ignored with no error.
Swapping Variables
We can swap the values of an array element with just a single line of code as opposed to using a temporary variable as was the case Pre ES6. Amazing right? Let me show you how:
let c = 10;
let m = 20;
[c, m] = [m, c];
console.log(m, c);
//Output
m = 20,
c = 10
Destructuring allows us to interchange the values of our array element seamlessly without breaking our backs. Easy right?
Destructuring Returned Arrays
In JavaScript, Array Destructuring makes working with a function that returns an array as a value more clear and readable. Let me show you what i mean:
function players () { return ["John", "Peter", "James"]};
let [x, y, z] = players();
console.log(x, y, z);
//Output
John, Peter, James
Ignoring returned values
With array destructuring, you can choose to either ignore returned values in arrays that you're not interested in or ignore all return values completely using trailing commas:,,
. Let me show you how:
function foo() {
return [5, 6, 7];
}
const [m, , o] = foo();
console.log(m);
//Output
5
console.log(o);
//Output
7
const [j] = foo();
console.log(j); // 5
In our code above, we deliberately ignored the second element 6
in our foo
array function using a trailing comma- ,
.
//You an also ignore all values
[,,,] = foo();
Our code snippet would return nothing when you console.log() because we have used three,,,
to skip all the values in the array. The comma separator is used to ignore values in an array. So if you want to skip an item on an array, just use a comma.
The Rest Parameter
In JavaScript, the Rest parameter is used to map elements that haven't been mapped before to the rest variable itself using the rest pattern ...
(three dots) . In the example below, we are going to use the Rest parameter to create new variables to the rest of the element in the array.
const cars = ["Sedan", "Coupe", "Station-Wagon", "Convertible", "Minivan", "Sport-Utility"];
let[first, second, ...others] = cars
console.log(first) // Sedan
console.log(second) //Coupe
console.log(others) //"Station-Wagon", "Convertible", "Minivan", "Sport-Utility"
Note two things here
- The rest operator must always be used as the last element in your array otherwise, it will throw a SyntaxError.
2.
The rest element must not have a trailing comma ,
after declaration
Let me show you what i mean:
const [m, ...n,] = [9, 10, 13]
console.log(m, n);
//Output
SyntaxError: Rest element must be last element
Assignment separate from declaration
Another astonishing feature of array destructuring is that we can use it to assign values to variables independent from the variable's declaration. Here's an example:
let Coupe, StationWagon;
[Coupe, StationWagon] = [ "MercedesBenz", "Volvo"];
console.log(Coupe); //MercedesBenz
console.log(StationWagon); //Volvo
Reference
Final Words
This is a follow-up on my last article on Object Destructuring .
Kindly leave a comment if you have any question or addition.
Thank you for reading :)