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 of the elements that come after the second one (null when the array has two or fewer elements)
  • restLength: How many elements sit between the second one and last (the ...rest array with last taken out of it)

If any of these elements don't exist, use default values of null. Example: for [1, 2, 3, 4, 5] the result is { first: 1, second: 2, last: 5, restLength: 2 }; for [42] it is { first: 42, second: null, last: null, restLength: 0 }.

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

Practice on your own: Online JavaScript compiler