DEV Community

Cover image for Destructuring Arrays in JavaScript
Quinn Lashinsky
Quinn Lashinsky

Posted on • Originally published at Medium

Destructuring Arrays in JavaScript

Destructuring is a new feature available in ES6. Destructuring allows you to assign elements in objects or arrays to variables in a swift, declarative way. We can reach into deeply nested structures and even eliminate the need to null check by grabbing just the elements we need, leading to more succinct code.

Let’s take a look at a couple of examples dealing with destructuring arrays:

One of my favorite television shows is Black Mirror, and I figure we could use the main overarching theme, season in and season out, as an example.

Grabbing the First Element:


const blackMirror = ['black', 'mirror', 'technology', 'bad']

const [first] = blackMirror

console.log(first) 
// 'black'

Grabbing All Of The Elements

const blackMirror = ['black', 'mirror', 'technology', 'bad']

const [first, second, third, fourth] = blackMirror

console.log(first) 
// 'black'  
console.log(second) 
// 'mirror'  
console.log(third) 
// 'technology'  
console.log(fourth) 
// 'bad'

Grabbing Non-Sequential/Out Of Order Elements

By using the comma operator, we can return each index we want to destructure and skip over the rest. It’s important to note that the comma is in addition to any other commas needed to separate elements.

const blackMirror = ['black', 'mirror', 'technology', 'bad']

const [first,,third] = blackMirror

console.log(first) 
// 'black'   
console.log(third) 
// 'technology'

Using the Spread Operator

const blackMirror = ['black', 'mirror', 'technology', 'bad']

const [firstElem, ...rest] = blackMirror

console.log(first) 
// 'black'  
console.log(rest) 
// ['mirror', 'technology', 'bad']  

As long as the right hand side of your destructuring assignment returns an array, you can destructure the elements in the array. This means functions or objects that return arrays can also be destructured.

Array Destructuring from an Object

const blackMirror = \['black', 'mirror', 'technology', 'bad'\]

const cereal = {  
    frosties: blackMirror   
}

const [first] = cereal.frosties

console.log(first) 
// 'black'

Array Destructing from a Function

function sugarPuffs(){  
    return blackMirror  
}  
const [,,third] = sugarPuffs()

console.log(third) 
// 'technology'

Array destructuring can help you write more effective, concise code by avoiding the need to declare extra variables and only destructuring the data necessary to building your application.

Top comments (0)