Skip to main content

Destructuring in JavaScript

Updated 3 min readMarkdown
Destructuring in JavaScript

What is Destructuring

Destructuring allows to extract values from objects and arrays and assign them to variables easily

Destructuring simply means breaking the structure, we simple break the structure of arrays or object into set of variables.

let agent = {
    name:"Jaskirat",
    location:"Pakistan",
    rank:2,
}

// instead of doing this
let name = agent.name;
let location = agent.location
let rank = agent.rank;

// simply do this
let {name,location,rank} = agent;

Destructuring from Arrays

Destructuring in arrays takes place based on the index.

let [country,populationInCr] = ["India",145];
console.log(`Population in \({country} has crossed \){populationInCr} Cr`);

// Output: Population in India has crossed 145 Cr

// the first index value enters in the first variable (country)
// second index value enters in the second variable (populationInCr)

Skipping the values

If you want to extract only some specified values from the array, we simply ignore the value by adding a ,

const money = [10,20,50,100];

// I want to give 120 rs to a vender
const [,twenty,,hundred] = money;
console.log(twenty+hundred) // 120

Collecting the remaining value using rest operator

If you only want to extract some values of entire array and keep the rest of the values in the array, we use the deadly combination of destructuring and rest ... operator


let tea = ["boil water","add sugar","add tea leaves","add milk","strain into a cup"]

const [firstStep,...remainingSteps] = tea;
console.log(firstStep)// boil water

console.log(remainingSteps); // [ 'add sugar', 'add tea leaves', 'add milk', 'strain into a cup' ]

Destructuring the object

We destructure the object using the key present in the object

let agent = {
    name:"Jaskirat",
    location:"Pakistan",
    rank:2,
}

let {name,location,rank} = agent;

Renaming the variable

We can rename the variable after destructuring

let plant = {
    name:"Mango",
    location:{city:"Ratnagiri",state:"Maharashtra"},
    price:50
}

let {name:nameOfPlant} = plant;
console.log(nameOfPlant); // mango

Extracting the nested values

let plant = {
    name:"Mango",
    location:{city:"Ratnagiri",state:"Maharashtra"},
    price:50
}

let {location:{city,state}} = plant;
console.log(`Location of plant is \({city} , \){Maharashtra}`); 

// Output Location of plant is Ratnagiri , Maharashtra

Default Values

You can provide an default value when key or index is not present in object or array

const user = {
  name: "John"
};

const { name, age = 18 } = user;

console.log(age); // 18
let [a,b,c="Banana"] = ["Mango","Orange"];
console.log(`Fruit at c is ${c}`);

// Output Fruit at c is Banana

Benefits of Destructuring

  • Cleaner Code : Without Destructuring, you need to individually extract value, destructuring made it easier

    // Without destructuring
    const name = user.name;
    
    // With destructuring
    const { name } = user;
    
  • Less Repetation : Using of object or array for continuous access is avoided using destructuring

    const user = { name: "A", age: 20 };
    
    // Instead of repeating "user"
    const { name, age } = user;
    
  • Easier Function Parameters :

    function greet({ name, age }) {
      console.log(`\({name} is \){age}`);
    }
    
    greet({ name: "John", age: 25 });
    
  • Improves Readability : Code becomes less verbose, More intutative and easy to understand and use

Good to Know

We can use the destructuring without actually assining it to let,const or var.
we need to wrap everyting inside ()

({ a, b } = { a: 1, b: 2 }); // Correct syntax for assignment without declaration

console.log(a); // 1
console.log(b); // 2

No comments yet. Be the first to comment.