Javascript ES6 Array & Object Destructuring

Sherlynn
2 min readAug 31, 2019

ES6 introduced a number of significant improvements to the language, including de-structuring of Objects and Arrays.

Array Destructuring

Traditionally, to access elements in an Array, you would do so with their index number like so:

const array = [1, 2, 3];console.log(array[0])
// 1

Javascript ES6 allows you to assign the array to another array that contains variables in the same index as the element you need.

You can do this:

const array = [1, 2, 3];const [first, second, third] = array;console.log(first, second, third); 
// 1 2 3

This works well for simple arrays. However, if you only want to assign variables to certain array elements, e.g. you want to assign a variable to the number 4 in the array; you would have to do something like this:

const array = [1, 2, 3, 4];const [, , ,fourth] = array;console.log(fourth); 
// 4

This introduces some code smells in terms of readability (unsightly commas) as well as maintainability. A developer (yourself or a team member) might easily miscount the number of those placeholders and introduce a bug to the code.
If you face a situation whereby you need to do the above, you may want to consider using Object Destructuring instead (below).

Object Destructuring

JavaScript Objects also have a de-structure syntax:

const obj = { key1: 'value1', key2: 'value2' };const { key1 } = obj;console.log(key1); 
// value1

You can then assign variable names for the object keys:

const { key1: first } = obj;console.log(first);
// value1

For the above Array example, we can avoid the use of the unsightly placeholders and use Object destructuring:

Array Destructing (with unsightly placeholders)const array = [1, 2, 3, 4];const [, , ,fourth] =…

--

--