Skip to content

#158 Destructuring Assignment

Adam Kubiś edited this page Oct 28, 2026 · 1 revision

158 Destructuring Assignment

You can assign variables from arrays like this: arr = [1, 2, 3, 4, 5, 6, 7, 8] first = arr[0] second = arr[1] third = arr[2] other = arr.slice(3)

console.log(first) ➞ outputs 1 console.log(second) ➞ outputs 2 console.log(third) ➞ outputs 3 console.log(other) ➞ outputs [4, 5, 6, 7, 8] However, this is long and tedious. Instead, we can use Object Destructuring to create all those variables in one line. Your task: Create variables first, second, third and other from the given array using Destructuring Assignment Your task is to unpack the arr writeyourcodehere into four variables, first, second, third, and other.

Current source and tests | Catalog | Testing and tooling

Run this solution

From the cloned repository root, after installing dependencies:

node "Edabit/158 Destructuring Assignment.js"

Assertions are kept alongside the implementation and throw on failure. A successful run exits with code 0. Run every exercise with npm test or both lint and tests with npm run check.

Current implementation and tests

This is the complete executable file, including its imports and inline test cases. Run it from the repository, not as an isolated file copied out of the wiki. Line endings and trailing whitespace are normalized; executable tokens are unchanged.

/*You can assign variables from arrays like this:
arr = [1, 2, 3, 4, 5, 6, 7, 8]
first = arr[0]
second = arr[1]
third = arr[2]
other = arr.slice(3)

console.log(first) ➞ outputs 1
console.log(second) ➞ outputs 2
console.log(third) ➞ outputs 3
console.log(other) ➞ outputs [4, 5, 6, 7, 8]
However, this is long and tedious.
Instead, we can use Object Destructuring to create all those variables in one line.
Your task: Create variables first, second, third and other from the given array using Destructuring Assignment
Your task is to unpack the arr writeyourcodehere into four variables, first, second, third, and other.*/
const writeyourcodehere = [1, 2, 3, 4, 5, 6, 7, 8]
const [first, second, third, ...other] = writeyourcodehere;
import { assertEquals } from '../testHelper.js';
assertEquals(first, 1)
assertEquals(second, 2)
assertEquals(third, 3)
assertEquals(other, [4, 5, 6, 7, 8])

Clone this wiki locally