De-structuring Assignment

Introduction

De-structuring is a special syntax that allows us to unpack arrays or objects into a bunch of variables, as sometimes that is more convenient.

De-structuring allows us to copy the array/object values into variables without modifying the array/object contents.

Array De-structuring

Example 1:

let arr = ["John", "Smith"];
let [firstName, surname] = arr;

console.log(firstName); // John
console.log(surname); // Smith

Example 2:

let [firstName, surname] = "John Smith".split(' ');
console.log(firstName); // John
console.log(surname); // Smith

Example 3: (ignoring unwanted values)

Suppose the array on the right is too large and the assignable on the left is too small, and we want to pick up only specific elements from the array on the right. This can be done in the following way:

let [firstName, ,title] = ["Julius", "Caesar", "Consul", "of the Roman Republic"];
console.log(firstName); // Julius
console.log(title); // Consul
  • Array de-structuring works with any iterable and not just arrays. This is because array de-structuring can be thought of as syntax sugar for the “for…of” loop. Think of it like it iterates over the array on the right, and assigns the right element to the assignable on the left.

  • The assignable on the left can be anything. It could be an object too.

let user = {};
[user.name, user.surname] = "John Smith".split(' ');

console.log(user.name); // John
console.log(user.surname); // Smith
console.log(user);

// { name: "John", surname: "Smith }
  • We can also use array de-structuring to swap variables.
let guest = "Jane";
let admin = "Pete";

[guest, admin] = [admin, guest];

console.log(guest); // Pete
console.log(admin); // Jane
  • Array de-structuring while looping with .entries()
let user = {
    name: "John",
    age: 30
};

for(let [key, user] of Object.entries(user)) {
    console.log(`${key}, ${user}`); 
}

/* name, John
        age, 30
*/
  • When the array on the right is too large than the assignable on the left, then it is not necessary to mention all the variables in the assignable list on the left. Using the rest operator we can copy all the elements from the right to the left. Let us understand this with the following example:
let [name1, name2, ...rest] = ["Julius", "Caesar", "Consul", "of the Roman Republic"];
console.log(name1);
console.log(name2);
console.log(rest.length); // 2;
console.log(rest[0]); // Consul
console.log(rest[1]); // of the Roman Republic
  • We can also provide default values when the values are missing in the array on the right.

    • The default values can be complex expressions or even function calls.

      let [name = "Guest", surname = "Anonymous"] = ["Julius"];
      console.log(name); // Julius
      console.log(surname) // Anonymous
      

Object De-structuring

  • De-structuring works with Objects too.
  • It involves de-structuring the keys from the object so that it can be used in a Javascript program.
let options = {
    title: "Menu",
    width: 100,
    height: 200
};

const {title, width, height} = options;

console.log(title); // Menu
console.log(width); // 100
console.log(height); // 200
  • We can provide aliases to the keys being de-structured from an object, so that the values to those keys can be accessed using the aliases.
let options = {
    title: "Menu",
    width: 100,
    height: 200
};

const {title: t, width: w, height: h} = options;

console.log(t); // Menu
console.log(w); // 100
console.log(h); // 200
  • We can also provide default values.
let options = {
    title: "Menu";
};

const {title, width = 100, height = 200} = options;

console.log(title); // Menu
console.log(width); // 100 since width as a key doesn't exist in the object
console.log(height); // 200 since height as a key doesn't exist in the object
  • We can use the rest operator to de-structure the keys in an object.
let options = {
    title: "Menu",
    width: 100,
    height: 200
};

const {title, ...rest} = options;

console.log(title); // Menu
console.log(rest.width); // 100
console.log(rest.height); // 200

Nested De-structuring

  • Complex Objects involving Objects as values associated with keys within an object and arrays associated with keys can be de-structured in the following way:
let foodData = {
    size: {
        width: 100,
        height: 200,
    },
    items: ["cake", "donut"],
    extra: true
};

let {size: {width: wide, height: high}, items: [item1, item2], extra: ex} = foodData;

console.log(wide); // 100
console.log(high); // 200
console.log(item1); // cake
console.log(item2); // donut
console.log(ex); // true

Smart Function Parameter

  • Objects passed as a parameter to a function can be de-structured for convenience and ease of use.
let options = {
    title: "My menu",
    items: ["cake", "donut"],
};

function showMenu({title = "Untitled", width = 100, height = 200, items: [item1 = "Hello", item2 = "World"]}) {
    console.log(`${title}, ${width}, ${height}, ${item1, item2}
};

showMenu(options);
  • We can pass in default values to a function parameter in case an empty object is passed to a function.
function showMenu({width = 100, height = 200}) {
    console.log(width); // 100
    console.log(height); // 200
};

showMenu({});

// 100
// 200

Links

I have attached the GitHub link to the code related to the topics covered in this blog. You can check it out for your reference.

All about Destructuring assignments

Final Thoughts

That was all about the de-structuring assignment in Javascript. Next, I will be discussing the date and time Object, JSON methods, and Recursion and stack. Stay tuned for more.

Thank you.

You can follow me on GitHub and LinkedIn.