Destructuring and REST Parameters

Destructuring and REST Parameters

ยท

2 min read

Destructuring

The two widely used data structures in JavaScript are arrays and objects. It is a way to unpack arrays and objects into a bunch of variables.

Array Destructuring

let arr = ["John", "Smith"]
//destructuring
let firstName = arr[0];
let secondName = arr[1];

console.log(firstName);               //John

and in the shorter way it can be written as:

let [firstName, lastName] = arr;
console.log(firstName);                                  //John

Object Destructuring

Same thing we can do with objects.

let {title, width, height} = {title: "Menu", width: 100, height: 200};
console.log(title);

One difference in object and array restructuring is that order doesn't matter in the case of objects. So, if we write above as:
let{height, title, width} = {title: "Menu", width: 100, height: 200};
It works the same.

REST Parameters

Whenever we call such a function in which we can pass any number of arguments, the REST parameter can be used. It is denoted using ... (three-dot characters).

function fun(...numbers)
{ 
      let sum=0;
      for(let num of numbers)
      {
            sum = sum + num;
      }
      return sum;
}

console.log(fun(1, 2, 3, 4, 5));           //15

We can also use it with an array of arguments. This spread out the array in the form of an individual element.

function fun(...numbers)
{ 
      let sum=0;
      for(let num of numbers)
      {
            sum = sum + num;
      }
      return sum;
}

let numbers = [1, 2, 3, 4, 5];
console.log(fun(...numbers));               //15

So, this was all about this topic. Thanks for reading!๐Ÿ˜Š

ย