Destructuring objects and arrays in JS

Declaring variables is something you learn on day one of your dev journey. In modern JS, it looks something like this:

let changeable = "This value may be updated and changed because my variable type is 'let'";
const unchangeable = "This value is set in stone and can never be changed because my type is 'const'";

Simple enough. But lets say you have a load of values in an array, like this.

const arr = ['apple', 'banana', 'cherry']

You could access and use them like so: arr[0], arr[1] etc. Thats fine for small arrays, but would get tedious with larger data sets, and having to reference items like arr[103] would make the code hard to read and understand.

However, there is a way to programmatically handle this using something called destructuring.

Array destructuring in Javascript

Using the example above, we can ‘destructure’ the array. This means new variables are created from the array’s values, like so:

const [one, two, three] = arr
console.log(two) // banana

If we were to do this the long and manual way, we’d have to write:

const one = arr[0];
const two = arr[1];
const three = arr[2];

Destructuring makes this quicker and easier to read and write.

You can also skip values in the array, like:

const [, , three] = arr;
console.log(three) // cherry

Or list more variables than the array has. These extra variables will just be initialised as undefined.

Object destructuring in JS

You can destructure objects too:

const obj = { 
  one: 1, 
  two: 2, 
  three: 3 
};

const { one, two, three } = obj;

Similar to arrays, this is the equivalent of doing:

const one = obj.one;
const two = obj.two;
const three = obj.three;

You can skip keys simply by leaving them out:

const {two, three} = obj
// 'one' is skipped

If a variable name doesn’t match a key, it will just be initialised as undefined rather than throwing an error:

const { one, two, threeeeeee } = obj;
console.log(threeeeeee) // undefined

You can also rename keys while destructuring, like so:

const {
  one: numberOne,
  two: numberTwo,
  three: numberThree
} = obj;

This kind of destructuring is commonly used in React components to extract specific values from the props object passed into the component, without having to reference props repeatedly.

Note: You can also use let instead of const here if you need to reassign the variables. But the difference between let and const is a topic for another post!:

let { one, two, three, four } = obj;