JavaScript array and object destructuring

Published December 30, 2020

JavaScript array and object destructuring allows us to break up arrays and objects into their individual pieces. Arrays and objects are the two most used data structures in JavaScript. Therefore, it will be very useful to know how to destructure them.

JavaScript objects make it easy for us to create a single entity that stores our data by key. JavaScript arrays help us to gather data into an ordered collection. The destructuring assignment syntax is useful for unpacking arrays or objects into the variables that we need from them.

Array Destructuring

Here is an example of a function that destructures an array into variables.

function printName(fullName) {
  const [firstName, lastName] = fullName;
  console.log(firstName); // John
  console.log(lastName);  // Smith
}

printName(['John', 'Smith']);

The destructuring assignment does not modify the original array. It just copies the array items into variables. It provides us with a quicker way of writing the following:

function printName(fullName) {
  const firstName = fullName[0];
  const lastName = fullName[1];
}

printName(['John', 'Smith']);

Skipping over elements

We can skip over elements that are not needed during destructuring.

const [firstName, , title] = ["John", "Smith", "President"];

console.log(firstName); // John
console.log(title); // President

Object properties on the left side

We can use object properties for the left-hand side of the destructuring syntax.

const person = {};
[person.firstName, person.lastName] = "John Smith".split(' ');
console.log(person.firstName); // John
console.log(person.lastName); // Smith

The split function broke up our string wherever a space was found. Since there was a space between John and Smith&, the string was broken up into an array of two elements containing John and Smith.

Array Destructuring with Sets

Array destructuring also works with JavaScript sets.

const [firstName, middleName, lastName] = new Set(['John', 'James', 'Smith']);
console.log(firstName); // John
console.log(middleName); // James
console.log(lastName); // Smith

Array Destructuring with the spread operator

We can use JavaScript spread syntax to get the remaining values of an array while destructuring.

const [firstName, middleName, ...data] = ['John', 'James', 'Smith', 'President'];

console.log(firstName); // John
console.log(middleName); // CaJamesesar
console.log(data[0]); // Smith
console.log(data[1]); // President
console.log(Array.isArray(data)); // true
console.log(data.length); // 2

Array Destructuring with default values

We can set a default value for any missing elements during destructuring.

const [firstName, lastName, title = 'No Title'] = ['John', 'Smith'];
console.log(firstName); // John
console.log(lastName); // Smith
console.log(title); // No Title

Object Destructuring

The destructuring assignment also works with objects. On the right side will be an existing object and on the left side will be the properties that we want to extract from it.

const car = {
  brand: 'Ford',
  model: 'Mustang',
  year: 1967
};

const { brand, model, year } = car;

console.log(brand); // Ford
console.log(model); // Mustang
console.log(year); // 1967

Object Destructuring with default values

We can also set default values while destructuring objects. It's similar to what we did while destructuring arrays.

const car = {
  brand: 'Ford',
  model: 'Mustang',
};

const { brand, model, year = 1995 } = car;

console.log(brand); // Ford
console.log(model); // Mustang
console.log(year); // 1995

If we have a complex object, we can destructure it into only the specific property that we need from the object.

const car = {
  brand: 'Ford',
  model: 'Mustang',
  color: 'Red',
  year: 1999,
};

const { brand } = car;

console.log(brand); // Ford

The default values can also be function calls. This also works for destructuring arrays.

const car = {
  brand: 'Ford',
};

let { brand = prompt("Enter Brand:"), model = prompt("Enter Model:") } = car;

console.log(brand); // Ford
console.log(model); // (Whatever the user enters in the model prompt)

Customizing destructured names

If we want to assign a property to a variable with a name other than the name of the object property, we can set a new name with the colon operator.

const car = {
  brand: 'Chevrolet',
  model: 'Corvette',
  year: 1967
};

const { brand: b, model: m, year } = car;

console.log(b); // Chevrolet
console.log(m); // Corvette
console.log(year); // 1967

The colon tells us what value goes where. For example, it allows the value for the variable brand to go into variable b.

Object Destructuring with the spread operator

If an object has more properties than we need variables, then we can assign the rest of the properties using the spread syntax. This is similar to what we did while destructuring arrays.

const options = {
  brand: 'Ferrari',
  model: 'Testarossa',
  year: 1984
};

const { brand, ...data } = options;

console.log(brand); // Ferrari
console.log(data.model);  // Testarossa
console.log(data.year);   // 1984

Abbreviated Destructuring

We can shorten the destructuring assignment syntax by not using let on the left-hand side and wrapping the expression in round brackets.

({ brand, model } = { brand: 'Ford', model: 'Mustang' });

console.log(brand); // Ford
console.log(model); // Mustang

model = 'Taurus';
console.log(model); // Taurus

Notice that brand and model will not be read-only references like we get with const.

Nested Destructuring

In this last example, the car object is comprised of other nested objects and arrays. We can use more complex left-side destructuring patterns to extract the deeper properties of the car object that we need.

const car = {
  type: {
    brand: 'Ford',
    model: 'Mustang',
    year: 1990,
  },
  attributes: {
    doors: 2,
    horsepower: 400,
  }
  features: ['Sunroof', 'Mags'],
  sold: true,
};

const {
  type: {
    brand,
    model,
  }, // get only the needed properties
  features: [featureOne, featureTwo], // assign features individually
  owner = 'John Smith' // not present in car (set a default value)
} = car;

console.log(brand);  // Ford
console.log(model);  // Mustang
console.log(featureOne); // Sunroof
console.log(featureTwo);  // Mags
console.log(owner);  // John Smith