JavaScript Destructuring Assignment

Profile picture for user arilio666

Destructuring Assignment is a general javascript expression that allows us to unpack values from arrays and properties from objects into unique variables data. This is done from arrays, objects, and nested objects. The most used are object and array.

Objects allow us to create a single entity that will enable us to store information items by key-value pair. The array allows us to gather data items into an ordered list.

Destructuring Assignment allows us to unpack arrays or objects into a bunch of variables and use those variables according to our convenience.

Array Destructuring

var arrList = ["apple", "orange", "pineapple"]

var fibre = arrList[0]
var vitc = arrList[1]
var heat = arrList[2]

console.log(fibre)
console.log(vitc)
console.log(heat)
  • So this is array destructuring, where the array items are stored in variables fetched by their index, therefore, destructuring it from there.
  • The variables can be used anytime with ease.
var arrList = ["apple", "orange", "pineapple"]

var [fibre, vitaminC, heat] = arrList

console.log(fibre)
console.log(vitaminC)
console.log(heat)
  • An array of variables are assigned here for the array stored data's variable arrList.
var [fibre, vitaminC, heat] = ["apple", "orange", "pineapple"]


console.log(fibre)
console.log(vitaminC)
console.log(heat)
  • Also, we can initiate the variables array and assign the data matching to it.
var [fibre,...otherFruits] = ["apple", "mango", "orange", "pineapple"];
         
console.log(fibre);
console.log(otherFruits);
  • With the rest operator, we can also call up variables and assign more data into a single variable stored in array form.

javascript destructure assignment

Object Destructuring

let fruits = {
    fibre: "Apple",
    vitC: "Orange",
    Heat: "Pineapple"
  };
  
  let {fibre, vitC, Heat} = fruits;
  
  console.log(fibre);  
  console.log(vitC);  
  console.log(Heat); 
  • Same as Array objects can also use destructuring Assignment just like after initializing the object.
  • Each variable is set in an object pattern and assigned with a fruits variable which will fetch all the values.
let fruits = {
    fruit1: "Apple",
    fruit2: "Orange",
    fruit3: "Pineapple"
  };
  
let {fruit1: fibre, fruit2: vitaminC, fruit3: heat} = fruits;

console.log(fibre)
console.log(vitaminC)
console.log(heat)
  • All the property variables are assigned with a key-value, the target variable set with all the fruits.
let fruits = {
    fruit1: "Apple",
    fruit2: "Orange",
    fruit3: "Pineapple"
  };
  
let {fruit1: fibre, ...otherfruits} = fruits;

console.log(fibre)
console.log(otherfruits.fruit2)
console.log(otherfruits.fruit3)
  • This is done with the ...rest pattern where two left-out variables will be accessible with the other fruits variable followed by a dot to access the two separately.