Member-only story

An Introduction to Destructuring in JavaScript

ML Musings
3 min readDec 27, 2022

--

Photo by Pankaj Patel on Unsplash

Destructuring is a feature in JavaScript that allows you to easily extract data from arrays or objects and assign them to variables. It is a concise and convenient way to access and manipulate data within arrays and objects, and it is especially useful when working with complex data structures.

Destructure an array:

let arr = [1, 2, 3, 4, 5];
let [a, b, c] = arr;
console.log(a); // 1
console.log(b); // 2
console.log(c); // 3

In this example, we are using destructuring to extract the first three elements of the array and assign them to variables a, b, and c. We can also use destructuring to assign the remaining elements of the array to a separate variable using the ... operator:

let arr = [1, 2, 3, 4, 5];
let [a, b, c, ...rest] = arr;
console.log(a); // 1
console.log(b); // 2
console.log(c); // 3
console.log(rest); // [4, 5]

Destructure a nested array:

let arr = [[1, 2], [3, 4], [5, 6]];
let [[a, b], [c, d], [e, f]] = arr;
console.log(a); // 1
console.log(b); // 2
console.log(c); // 3
console.log(d); // 4
console.log(e); // 5
console.log(f); // 6

Destructure an object:

let obj = {a: 1, b: 2, c: 3};
let {a, b, c} = obj;
console.log(a); // 1
console.log(b); // 2
console.log(c); // 3

--

--

ML Musings
ML Musings

Written by ML Musings

✨ I enjoy pushing the boundaries of JS, Python, SwiftUI and AI. You can support my work through coffee - www.buymeacoffee.com/MLMusings

No responses yet