Array Destructuring
Part of the Logic & Flow section of Coddy's JavaScript journey — lesson 47 of 65.
Array destructuring is a convenient way to extract multiple values from an array and assign them to variables in a single statement. It uses a syntax that mirrors the structure of an array literal.
Basic syntax:
const [a, b, c] = [1, 2, 3];
console.log(a); // 1
console.log(b); // 2
console.log(c); // 3You can skip elements:
const [a, , c] = [1, 2, 3];
console.log(a); // 1
console.log(c); // 3You can use rest parameters to capture remaining elements:
const [a, ...rest] = [1, 2, 3, 4, 5];
console.log(a); // 1
console.log(rest); // [2, 3, 4, 5]You can provide default values:
const [a, b, c = 3] = [1, 2];
console.log(c); // 3Challenge
EasyCreate a function called analyzeArray that takes an array as an argument. The function should use array destructuring to extract the first, second, and last elements of the array. It should return an object with the following properties:
first: The first element of the arraysecond: The second element of the arraylast: The last element of the arrayrestLength: The number of remaining elements in the array
If any of these elements don't exist, use default values of null.
Cheat sheet
Array destructuring extracts multiple values from an array and assigns them to variables in a single statement:
const [a, b, c] = [1, 2, 3];
console.log(a); // 1
console.log(b); // 2
console.log(c); // 3Skip elements by leaving empty spaces:
const [a, , c] = [1, 2, 3];
console.log(a); // 1
console.log(c); // 3Use rest parameters to capture remaining elements:
const [a, ...rest] = [1, 2, 3, 4, 5];
console.log(a); // 1
console.log(rest); // [2, 3, 4, 5]Provide default values for missing elements:
const [a, b, c = 3] = [1, 2];
console.log(c); // 3Try it yourself
function analyzeArray(arr) {
// Write your code here
}
This lesson includes a short quiz. Start the lesson to answer it and track your progress.
All lessons in Logic & Flow
1Strings In Depth
String FundamentalsIterate Over StringsTemplate LiteralsString MethodsRecap - String Weaver4JSON Part 2
Iterate Over JSONNested JSONJSON Optional ChainingShallow And Deep CopyRecap - Bicycle ShopRecap - Solar System10Manage Festival System
Project OverviewAdd Movies & Venues2Multi-dimensional Arrays
2D Arrays BasicsAccessing 2D Array ElementsNested Loops with 2D ArraysRecap - 2D ArraysMatrix Addition & SubstractionJagged Arrays3D Arrays And BeyondCommon 2D Array PatternsRecap - All About Arrays5Sets Part 1
What Is A Set?Iterating Over SetsAdding An ElementRemoving An ElementChecking If An Element ExistsSize And Is EmptyCopy And ClearRecap - Basic Of Sets8Arrays Interesting Topics
Array DestructuringSpread Syntax in ArraysSparse ArraysRecap - Arrays Workshop3JSON Part 1
What is a JSON?Check If Key ExistsObject MethodsThe Spread Operator Part 1The Spread Operator Part 2Remove KeysRecap - JSON Manipulate Keys