Array destructuring was introduced in ES6 version of Javacsript
Array destructuring in Javascript allows you to unpack values from arrays into distinct variables in a clean, readable way. Here are the most common use cases for array destructuring:
1. Basic variable assignment
Before ES6
var arr = ['sujay', 23, 'engineer'];
var first = arr[0];
var second = arr[1];
console.log(first, second); // sujay 23
JavaScriptAfter ES6
Array destructuring is similar to object destructuring but it uses array literals syntax [].
let arr = ['sujay', 23, 'engineer', 'javascript'];
let [first, second] = arr; // destructured
console.log(first, second); // sujay 23
JavaScript2. Skipping Items
If we want to skip and access values at other positions then we can do so by keeping that position blank.
let [first, ,third] = arr; // we have kept the second position blank
console.log(first, third); // sujay engineer
JavaScript3. Default values
We can also assign default values to the variables.
let [,second,,fourth, fifth = 'default value'] = arr;
console.log(second, fourth, fifth); // 23 javascript default value
JavaScript4. Rest Elements
We can also use rest operator (…) to gather all the remaining array values in any variable.
let [first, ...remaining] = arr;
console.log(first, remaining); // sujay [23, 'engineer', 'javascript']
JavaScript5. Nested Array Destructuring
It is also possible to do nested array destructuring.
// Example 1
const arr = [1, [2,3]];
const [a, [b,c]] = arr;
console.log(a); // 1
console.log(b); // 2
console.log(c); // 3
// Example 2
let arr = ['sujay', 23, 'engineer', ['random', 'bangalore', 560060]];
let [first,,,[,city, zip, state='Karnataka']] = arr;
console.log(first, city, zip, state); // sujay bangalore 560060 Karnataka
JavaScript6. Swapping with Array Destructuring
We can swap values very easily with an array destructuring.
let first = 1;
let second = 2;
console.log(first, second); // 1 2
// swap
[first, second] = [second, first]
console.log(first, second); // 2 1
JavaScript7. Cloning an array with destructuring
let arr = [2,3,5,6];
let [...cloned] = arr;
console.log(cloned); // [2,3,5,6]
JavaScript8. Mixed destructuring in Javascript
We can use Array and Object Destructuring simultaneously.
let person = {
name: 'sujay kundu',
age: 23,
address: {
street: 'random',
city: 'bangalore',
pincode: 560060
},
phone: [9324343433,9232334342, 9023343434]
}
let {
name,
address: { street: streetAddress},
phone: [firstPhoneNum]
} = person;
console.log(name, streetAddress, firstPhoneNum);
// sujay kundu random 9324343433
JavaScript9. Destructuring with Functions
We can use destructuring with parameters passed to the functions.
let person = {
name: 'sujay kundu',
age: 23,
address: {
street: 'random',
city: 'bangalore',
pincode: 560060
},
phone: [92423423433, 9232334342, 9023343434]
}
let showDetails = ({name, age}) => {
console.log(`${name} is ${age} years old`};
}
showDetails(person); // sujay kundu is 23 years old.
JavaScript10. For-of loops with Destructuring
Array destructuring can be used within a for-of loop.
const arr = [[1,2], [3,4]];
for (const [a,b] of arr) {
console.log(a, b);
}
// Output:
// 1 2
// 3 4
JavaScript11. Combining with Object Destructuring
You can combine array destructuring with object destructuring for more complex data structures.
const arr = [
{
name: "Alice",
age: 25
}, {
name: "Bob",
age: 30
}];
const [
{
name: firstName
}, {
age: secondPersonAge
}
] = arr;
console.log(firstName); // Alice
console.log(secondPersonAge); // 30
JavaScript12. Multiple Return values from Promise
You can destructure arrays returned from Promise.all
const promise1 = Promise.resolve(3);
const promise2 = Promise.resolve(42);
Promise.all([promise1, promise2]).then([result1, result2]) => {
console.log(result1); // 3
console.log(result2); // 42
});
JavaScript13. Extracting values from split strings
Use destructuring to easily extract values from a string split operation.
const [firstName, lastName] = "John Doe".split(' ');
console.log(firstName); // John
console.log(lastName); // Doe
JavaScript14. Limiting Destructuring Length
You can limit you many values you unpack from an array, even if the array has more values.
const arr = [1, 2, 3, 4];
const [a, b] = arr;
console.log(a); // 1
console.log(b); // 2
JavaScriptThese use cases highlight how versatile array destructuring can be for simplifying variable assignments, working with complex data structures, and writing clean code.
Pingback: Javascript - ES6 Features - xplor4r