Skip to content

8 Ways of Using Destructuring Assignment in JavaScript

JavaScript/

You can achieve cleaner and shorter code by replacing many repetitive assignments with a destructuring assignment. It extracts individual values from arrays and objects into variables in one statement. In this article you will learn 8 ways to use the destructuring assignment.

1. Variable Assignment

Without destructuring assignment, extracting values of an array into individual variables one by one is tedious.

const fruits = ['Apple', 'Orange', 'Melon'];
const apple = fruits[0];
const orange = fruits[1];
const melon = fruits[2];

That’s a lot of typing. Luckily, the same can be achieved in one assignment, instead of three, using the destructuring assignment.

const fruits = ['Apple', 'Orange', 'Melon'];
const [apple, orange, melon] = fruits;

Destructuring assignment extracts the first element of fruits array into apple variable, the second into orange and so on. Destructuring assignment expects an identifier (name of a variable) for every value you want to grab from the array. The identifiers must be enclosed in square brackets ([]) and separated from each other with commas (,). The order of the identifiers matches the order of the elements in the array.

You can also assign property values of an object to variables in almost the same way. Difference is, you must wrap the identifiers in curly braces ({}).

const person = { name: 'John', age: 42 };
const { age, name } = person;

console.log(name); // John

The identifiers must match the keys of the properties you want to extract from the object. For example, the name variable will be assigned the value of person.name. The order of identifiers doesn’t matter because object properties are unordered.

Don’t Extract Certain Values

You don’t have to extract every value.

With arrays, leave the variable name empty for the values you want to skip. However, you still have to put a comma (,) to separate the identifiers, even if they are “invisible”.

const fruits = ['Apple', 'Orange', 'Banana', 'Melon'];

const [, , banana] = fruits; // Skip 1st and 2nd

const [, orange, , melon] = fruits; // Skip 1st and 3rd

// Orange Banana Melon
console.log(orange, banana, melon);

Are you wondering what happened to the 4th element on line 3? You can skip extracting all the remaining values after a certain element, if you don’t provide any variables for them.

const fruits = ['Apple', 'Orange', 'Banana', 'Melon'];

const [apple] = fruits; // Take only the 1st

// Apple
console.log(apple);

It’s easier for objects. Just don’t specify identifiers for the properties you don’t want.

const person = { name: 'John', age: 42 };
const { name } = person;

console.log(name); // John

2. Rest Property

Rest property works similarly to the rest parameter in functions. It is a variable that collects all the values you haven’t provided an identifier for.

When destructuring an array, the values get collected into an array. But for objects, properties get placed into an object.

It is useful when you want to extract only some values into individual variables, but still have a container for all the other values.

Rest property must come as the last identifier.

const fruits = ['Apple', 'Orange', 'Banana', 'Melon'];

const [apple, ...restOfFruits] = fruits;

// Apple [ 'Orange', 'Banana', 'Melon' ]
console.log(apple, restOfFruits);

const person = {
  name: 'Nina',
  age: 25,
  job: 'developer',
};

const { job, ...nina } = person;

// Nina(25) is a developer
console.log(`${nina.name}(${nina.age}) is a ${job}`);

3. Default Values

What happens if you try to extract a value that doesn’t exist? That value is undefined.

const fruits = ['Apple'];
const [apple, melon] = fruits;

// Apple undefined
console.log(apple, melon);

const person = { age: 63 };
const { name, age } = person;

// undefined 63
console.log(name, age);

You can provide a fallback to avoid undefined values. The variable will only use your given default value if the extracted value is undefined.

const fruits = ['🍎'];
const [apple = 'Apple', melon = 'Melon'] = fruits;

// 🍎 Melon
console.log(apple, melon);

const person = { age: 63, name: undefined };
const { name = 'Susan', age } = person;

// Susan 63
console.log(name, age);

4. Variable Reassignment

You can extract values into already defined variables.

let carrot = 'Carrot';
let broccoli = 'Broccoli';
const vegetables = ['🥕', '🥦'];

[carrot, broccoli] = vegetables;

// 🥕 🥦
console.log(carrot, broccoli);

There is small difference when destructuring objects, you must wrap the assignment in parentheses (()).

let name = 'Jack';
let age = 30;
const anotherPerson = { name: 'Anna', age: 23 };

({ name } = anotherPerson); // Override only the name

// Anna 30
console.log(name, age);

5. Destructuring Nested Values

Destructuring assignment can be used to extract nested values. For example, you can grab the values of an array that is an element of another array.

Wrap the variables in additional pair of brackets when extracting nested array values.

const foods = [
  ['Apple', 'Orange'],
  ['Carrot', 'Broccoli'],
];

const [fruits, [carrot, broccoli]] = food;

// [ 'Apple', 'Orange' ]
console.log(fruits);

// Carrot Broccoli
console.log(carrot, broccoli);

The deeper you go, the more brackets you add.

const example = ['unnested', [['deeply nested']]];

const [one, [[two]]] = example;

// deeply nested
console.log(two);

You can also extract properties of nested objects. In other words, objects are properties inside of another object.

Specify the parent property that contains the object first. Then specify the keys of the properties you want to extract from the child object. Of course, don’t forget the {}.

const user = {
  name: 'Sally',
  address: {
    city: 'Big City',
    street: 'Green street',
  },
};

const {
  name,
  address: { street, city },
} = user;

// Sally lives on Green street
console.log(`${name} lives on ${street} in ${city}`);

You can destructure a mix of objects and arrays for some wild assignments.

const user = {
  name: 'Pamela',
  friends: [
    { name: 'Josh', age: 52 },
    { name: 'Nicky', age: 43 },
  ],
};

const {
  friends: [, { name: bestFriend }],
} = user;

// Nicky
console.log(bestFriend);

This example starts with destructuring the user object. Then, destructuring the friends property from user extracts an array. Destructuring that array provides access to its values. The first element of the friends array gets skipped by providing a comma (,). Finally, destructuring the second element, the name property gets extracted into a variable called bestFriend.

6. Alternative Identifiers

When destructuring an array, you can choose identifiers as you please. It’s not the same for objects. So far, you were limited to the keys of the object.

You can actually change the name of the variable that will hold the extracted object property.

Specify the name of the property first, as per usual. But then, place a colon after it and provide your own identifier. Like this - keyOfProperty: identifier.

const person = {
  name: 'Jack',
};

const { name: jack } = person;

// Jack
console.log(jack);

This is useful when working with properties that contain characters that are invalid for naming variables.

const user = {
  'user-name': 'superman12',
  age: 34,
};

const { 'user-name': userName, age } = user;

// superman12
console.log(userName);

In this case, you must provide an alternative identifier. The name of a variable can’t contain a hyphen (-).

7. Computed Object Property Names

A property name of an object isn’t always known while writing the code. Sometimes it is computed when your program is running.

// This name could be anything
// Perhaps, a user can change it
let computedProperty = 'evaluatedName';

const object = {
  regularProperty: 'I am a property',
  [computedProperty]: 'I am a computed property',
};

// I am a computed property
console.log(object[computedProperty]);

You can destructure these computed properties by wrapping them in [] and providing an alternative identifier.

const computedProperty = 'evaluatedName';

const object = {
  regularProperty: 'I am a property',
  [computedProperty]: 'I am a computed property',
};

const { [computedProperty]: myIdentifier } = object;

// I am a computed property
console.log(myIdentifier);

8. Function arguments

Destructuring can be used on function arguments.

You can grab only the properties that you are interested in when passing an object to a function.

function printUserInfo({ name, age }) {
  console.log(`${name} is ${age} years old`);
}

const user = {
  name: 'John',
  age: 28,
};

// John is 28 years old
printUserInfo(user);

You can also define default values for properties that the object might not have.

function printUserInfo({ name, job = 'Unknown' }) {
  console.log(`${name}'s current job: ${job}`);
}

const user = {
  name: 'John',
};

// John's current job: Unknown
printUserInfo(user);

Rest property and renaming can be used as well.

function printUserInfo({ name: userName, ...otherProperties }) {
  console.log(userName, otherProperties);
}

const user = {
  name: 'John',
  age: 35,
  job: 'Developer',
};

// John { age: 35, job: 'Developer' }
printUserInfo(user);

And, of course, arrays in function arguments can be destructed as well.

function printMealAndLeftovers(meal, [first, second, ...rest]) {
  console.log(`I ate ${first} with ${second} for ${meal}`);

  const leftovers = rest.join(' and ');
  console.log(`I left ${leftovers} for later`);
}

// I ate eggs with bacon for breakfast
// I left apple and pancakes for later
printMealAndLeftovers('breakfast', ['eggs', 'bacon ', 'apple', 'pancakes']);

References