Showing posts with label destructuring array. Show all posts
Showing posts with label destructuring array. Show all posts

Tuesday, 31 December 2019

Destructuring in JavaScript


JavaScript supports the extraction of values from an arrays and objects into variable. This is called as Destructuring.

Destructuring Objects:


let employee = {name:"abc", department:"finance", age:30};

// Extraction before ES6 it would be like this

let empName = employee.name;
let empDept = employee.department;
let empAge = employee.age;

// Using object destructuring it would be like this

let {name:empName, department:empDept, age:empAge} = employee;

console.log(empName); // abc
console.log(empDept); // finance
console.log(empAge); // 30

// To extract properties into variables with the same name would be like this:

let {name, department, age} = employee;

// Its not necessory to extract all the properties. We can also do like this:

let {department, age} = employee;

console.log(department); // finance
console.log(age); // 30


Destructuring Arrays:

let cricket = ["virat", "rohit", "dhoni"];

// destructuring would be like this

let [x, y, z] = cricket;

console.log(x); // virat
console.log(y); // rohit
console.log(z); // dhoni

// So array destructuring works based on the index in the array

Destructuring in Function Parameters:

// Typical method to pass multiple parameters (as an object) to function would be like this

function employee(params){
  console.log(params.empName); // abc
  console.log(params.empAge);  // 30
}

let empObj = {empName:"abc", empAge:30};
employee(empObj);

// Using object destructure pattern we can define function parameter like this:

function employee({empName, empAge}){
  console.log(empName); // abc
  console.log(empAge);  // 30
}

let empObj = {empName:"abc", empAge:30};
employee(empObj);

// In the above function we can directly refer to empName and empAge.

// We can also provide default value using destructure pattern, ex:

function employee({empName, empAge=25}){
  console.log(empName); // xyz
  console.log(empAge); // 25
}

employee({empName:"xyz"});

// so even though we have not passed empAge to employee function, it is taking a default age i.e. 25