Object Destructuring in JavaScript

     Object destructuring is a way to break a complex structure into simpler parts. Many times we want to assign pieces of a complex data structure to variables. Before it was tedious to do, but with JS Object Destructuring it is much simpler to do.

Consider the example,

const task = {
  procedure: "addition",
  numbers: {
    a: 25,
    b: 13,
    c: 85,
  },
};

Without destructuring, we need to do something like

function calculate() {
  const a = task.numbers.a;
  const b = task.numbers.b;
  const c = task.numbers.c;
  return a + b + c;
}

Or

function calculate() {
  return task.numbers.a + task.numbers.b + task.numbers.c;
}

It repeats the same code to access the required data from the structure.

Destructure

Now let's see how we would do this the modern way, with object destructuring.

const task = {
  procedure: "addition",
  numbers: {
    a: 25,
    b: 13,
    C: 85,
  },
};
function calculate() {
  const { a, b, c } = task.numbers;
  return a + b + c;
}

Default Values

Another great feature is default values. We don't have to check if some properties exist before destructuring. Just do this.

const task = {
  procedure: "addition",
  numbers: {
    a: 25,
    b: 13,
    c: 85,
  },
};
function calculate() {
  const { a, b, c, d = 0 } = task.numbers;
  return a + b + c + d;
}

Here we give the value 0 to the variable "d" while destructuring.

Changing Names

We can change the name of variables while destructuring

const task = {
  procedure: "addition",
  numbers: {
    a: 1,
    b: 2,
    c: 3,
  },
};
function calculate() {
  const { a: one, b: two, c: three, d: four = 4 } = task.numbers;
  return one + two + three + four;
}

Nested Destructuring

We can even destructure inside a destructure. This can be useful to reduce a bunch of code in more complex situations.

const task = {
  procedure: "addition",
  numbers: {
    a: 25,
    b: 13,
    c: 85,
  },
};
function calculate() {
  const {
    procedure,
    numbers: { a, b, c, d = 0 },
  } = task;
  if (procedure === "addition") return a + b + c + d;
  return null;
}



Comments

Popular posts from this blog

LeetCode 350: Intersection of Two Arrays II

LeetCode 35: Search Insert Position

LeetCode 217: Contains Duplicate