Menu
Coddy logo textTech

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); // 3

You can skip elements:

const [a, , c] = [1, 2, 3];
console.log(a); // 1
console.log(c); // 3

You 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); // 3
challenge icon

Challenge

Easy

Create 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 array
  • second: The second element of the array
  • last: The last element of the array
  • restLength: 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); // 3

Skip elements by leaving empty spaces:

const [a, , c] = [1, 2, 3];
console.log(a); // 1
console.log(c); // 3

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]

Provide default values for missing elements:

const [a, b, c = 3] = [1, 2];
console.log(c); // 3

Try it yourself

function analyzeArray(arr) {
  // Write your code here
}
quiz iconTest yourself

This lesson includes a short quiz. Start the lesson to answer it and track your progress.

All lessons in Logic & Flow