Adebiyi Adedotun
Apr 10, 2018 · 4 min read

Destructuring in JavaScript: What nobody told me!

It is not unusual to try to use properties off JS Objects and Arrays as a JavaScript developer. Just into my third chapter of learning JS, I found this common act my daily bread. ES6 makes it even simpler, because why not?

Let’s dive into it. We’ll go through some basic examples and dive right into the WHAT nobody told me, that should be told.

Code 1: Destructuring Objects

const person = { firstName: 'Adebiyi',  lastName: 'Adedotun' };

In the snippet above, let’s assume I decide to target the firstName variable of the person object, before ES6, I’d go:

// Before ES6
const firstName = person.firstName;
const lastName = person.lastName;

Imagine the depths results from API calls can take us to, then imagine how deep these nested properties can take to get to, and how ridiculous.

With ES6, I can write the same code with:

const { firstName, lastName } = person;

Let’s break down the syntax:

  1. The curly brace {} which denotes an Object, should be used for two reasons:
  • To let the JS interpreter know we are extracting variable off an Object and nothing else that can also be destructured — Sets, Maps and Arrays.
  • To include more than one variable off the Object in a comma-separated list, and not just variable declarations and initialization. This is so because if we tried:
1. const firstName, lastName = person; //error
2. let firstName, lastName = person; //no-error
3. var firstName, lastName = person; //no-error

without the curly braces, in line (1) I get a missing initializer in const declaration, and no error in line (2) and (3). Simply, because const variables must can only be instantiated, not declared. In (2) and (3), firstName is just initalized to undefined.


Code 2: Destructuring Arrays

With Arrays, the rules are quite different, for obvious reasons, one being that Arrays are not Objects and vice-versa.

Take this code:

const binaryNumbers = [0, 1];

Of course, before ES6, we’d go:

const firstNumber = binaryNumbers[0];
const secondNumber = binaryNumbers[1];

These syntax isn’t bad at all; there’s just a better syntax and readable way for both the computer and the programmer.

With ES6:

const [firstNumber, secondNumber] = binaryNumbers;

The syntax also contains:

  1. The square brackets used to denote Arrays.
  2. The brackets are also necessary for same reasons as for Objects.
const firstNumber, secondNumber = binaryNumbers; // error
let[firstNumber, secondNumber] = binaryNumbers; // no-error
var[firstNumber, secondNumber] = binaryNumbers; //no-error

And here comes what nobody told me:

The moment I saw these aspect of JS, I was glad because I knew it’d become a very important tool for me. I also noticed, after a tiring time of missing the syntax that:

  1. For Objects, the Left-Hand-Side variable mapping to the Right-Hand-Side Object, is done with KEYS, because Objects store their values with Keys already. It makes easy the rearrangement of extracted variables. In the person object above, I could have done:
const { lastName, firstName } = person;

i.e put the lastName before the firstName and I still get the desired result (Adedotun and Adebiyi, respectively), because the interpreter just checks the Object and fishes out the variables — unlike arrays.

2. For Arrays, it is different. It is wrong to do:

const[secondNumber, firstNumber] = binaryNumbers;

because Arrays store their values in indices. Therefore, the first value destructured is mapped to the value in the first index of the Array, and the second value destructured is mapped to the value in the second index of the Array… Which means. secondNumber is mapped to binaryNumbers[0] and firstNumber to binaryNumbers[1], which isn’t what is expected.

In JS destructuring, the LHS and RHS mapping of Objects are done with KEYS, while for Arrays, it is done with INDEX.


JS destructuring goes deeper than this, not just Arrays and Objects, with Sets and Maps too.

  1. Destructured values can also be re-named if needed, Or, given default values:
const person = {name: 'Dara Oladapo'};
const { name: fullName = 'Oladapo'} = person;
// fullName = Dara Oladapo

which means, take the variable name out of the object person and rename it fullName; if the variable name does not exist, create a variable called fullName and give it the default value ‘Oladapo’.

2. Destructuring can also be used for Variable Swapping:

//Before ES6
let inRing = 'The Undertaker';
let onSide = 'Kane';
console.log(`inRing = ${inRing}, onside = ${onSide}`);let temp = inRing; // 1
inRing = onSide; // 2
onSide = temp; // 3
console.log(`inRing = ${inRing}, onside = ${onSide}`);--------------------------------------------------------------
//with ES6, remove // 1, //2 and // 3 and replace with:
[inRing, onSide] = [onSide, inRing];

I think destructuring was done right in all ways, even with a simple syntax — once you get the hang of it, you really won’t stop using it.

It even helps with those code like:

doStuff(undefined, 'Why pass undefined at all?');

…when you can just pass an Object, and destructure it directly, like:

doStuff({message});

🤝Thanks for reading. Please feel free to help me improve this post and my blogging about programming in general. Leave a ‘clap’, it’d help me grow as a programmer — I’m less than a year into Web Development in general, and I feel writing about these things will help me grow.

Welcome to a place where words matter. On Medium, smart voices and original ideas take center stage - with no ads in sight. Watch
Follow all the topics you care about, and we’ll deliver the best stories for you to your homepage and inbox. Explore
Get unlimited access to the best stories on Medium — and support writers while you’re at it. Just $5/month. Upgrade