Nearby lessons
9 of 22JavaScript: Destructuring Arrays
π What is Array Destructuring?
Array destructuring in JavaScript is a concise way to extract values from arrays and assign them to variables. It simplifies code and improves readability, especially when dealing with arrays with multiple elements or nested arrays.
1οΈβ£ Traditional vs Destructuring Syntax
Without destructuring, each value must be accessed individually using indexes. With destructuring, values are unpacked directly into variables.
Code Example
2οΈβ£ Using Default Values
You can assign default values in case a value is undefined in the array.
Code Example
3οΈβ£ Destructuring Nested Arrays
Destructuring works on nested arrays too by using nested patterns.
Code Example
4οΈβ£ Using Rest Operator in Destructuring
The rest operator (...) can be used to collect remaining values into a single array.
Code Example
5οΈβ£ Destructuring Parameters in Functions
You can directly destructure an array passed to a function inside its parameter list.
Code Example
6οΈβ£ Returning and Destructuring Array from Function
Destructuring is helpful when functions return arrays. You can extract each item directly.