Array Destructuring
Array destructuring in JavaScript is a convenient way of extracting multiple values from arrays and assigning them to variables in a single statement. This syntax is introduced in ES6 (ECMAScript 2015) and allows for cleaner and more readable code.
Key Features
- Basic Destructuring: Extracts values from arrays and assigns them to variables.
- Default Values: Provides default values if the array element is
undefined. - Skipping Items: Skips over certain items in the array.
- Rest Syntax: Collects the rest of the elements into a new array.
Examples
Basic Destructuring
Extracting values from an array and assigning them to variables:
const numbers = [1, 2, 3];
const [a, b, c] = numbers;
console.log(a, b, c); // Output: 1 2 3
Default Values
Providing default values for variables:
const numbers = [1, 2];
const [a, b, c = 3] = numbers;
console.log(a, b, c); // Output: 1 2 3
Skipping Items
Skipping over certain items in the array:
const numbers = [1, 2, 3, 4];
const [a, , b] = numbers;
console.log(a, b); // Output: 1 3
Rest Syntax
Using rest syntax to collect the remaining elements into a new array:
const numbers = [1, 2, 3, 4, 5];
const [a, b, ...rest] = numbers;
console.log(a, b); // Output: 1 2
console.log(rest); // Output: [3, 4, 5]
Additional Information and Challenges
- Nested Destructuring:
- You can destructure nested arrays.
- Example:const nestedArray = [1, [2, 3], 4]; const [a, [b, c], d] = nestedArray; console.log(a, b, c, d); // Output: 1 2 3 4
- Using with Functions:
- Destructuring can be used with function parameters.
- Example:function sum([a, b]) { return a + b; } console.log(sum([1, 2])); // Output: 3