In this javascript array destructuring tutorial i wil show you details that how we can destructuring array in javascript. Javascript array destructuring is a useful JavaScript feature to extract properties from array and bind them to variables.
We can destructure single array or nested array in Javascript. You will also learn destructuring nested array in Javascript from this example.
Did you know that array destructuring can extract multiple properties in one statement, can access properties from nested array, and can set a default value if the property doesn’t exist yet in your array.
Let's take a look
var arr = ["Hello", "World"]
// destructuring assignment
var [first, second] = arr;
console.log(first); // Hello
console.log(second); // World
In this above example, Here var [first, second] = arr
is an object destructuring assignment. If we want to destructure the array into multiple properties, enumerate as many properties as you like adding commas ,
in-between:
const [ identifier1, identifier2, ..., identifierN ] = expression;
We can destructure nested array in javascript like When we work with nested array destructuring the corresponding item might be an array in order to use a nested destructuring array literal to assign items in it to local variables.
const numbers = [1,2,3,[11,22,33]];
const [one,two,three,[eleven, twelve, thirteen ]] = numbers
console.log(one) //1
console.log(eleven) //11
We can skip items by using the comma. One comma skips one item.
const numbers = [1,2,3];
const [,,three] = numbers;
console.log(three); //3
Read also: How to Do Object Destructuring in JavaScript
Hope it can help you.
#javascript