Family Magazine

Destructing Arrays in JavaScript (2023)

By Geoff Griffiths @mmatraining1980

Destructing an array sounds fun, but it’s not.

When we talk about “destructuring” an array, we’re referring to a process where we extract data from arrays, and assign them to variables in a single line. Here’s a basic example:





let array = [1, 2, 3, 4, 5];

// Destructuring the array
let [a, b, c, d, e] = array;

console.log(a); // Output: 1
console.log(b); // Output: 2
console.log(c); // Output: 3
console.log(d); // Output: 4
console.log(e); // Output: 5

In the above code, we’re taking an array of numbers, and using destructuring to assign each number to a variable (a, b, c, d, e).

You can also selectively choose which elements to extract. For example:

let array = ['apple', 'banana', 'cherry', 'dates', 'elderberry'];

// Destructuring the array
let [fruit1, , fruit3] = array;

console.log(fruit1); // Output: apple
console.log(fruit3); // Output: cherry

In this example, we're extracting the first and third elements from the array, while skipping the second element.

"Destructuring" can be particularly useful when you want to quickly access specific data in an array or an object without having to access them using their indexes or keys, respectively.

So, think about breaking the array apart, when you’re thinking about “destructing”

Examples from scaler.com

  • Array Destructuring:




var a, b;
[a, b] = [5, 10];
console.log(a); // 5
console.log(b); // 10
  • Object Destructuring:
({ a, b} = { a: 5, b: 10 });
console.log(a); // 5
console.log(b); // 10

Back to Featured Articles on Logo Paperblog