Destructuring: Destructuring is the process of extract data from a data structure .
lets see an example,
//ES5
var data = ['lokman',1989];
console.log(`data ${data}`);
var name=data[0];
var yearOfBirth=data[1];
console.log(`name=${name} year of birth=${yearOfBirth}`);
Here, we need two variable to extract data from the 'data' data structure in es5.
But we can do this by using destructuring in es6.
const [name,yearOfBirth]=['lokman',1989];
console.log(name);
console.log(yearOfBirth);
here ,name and yearOfBirth will be two variable to store data from the array .
We can extra properties from object using destructure. let's do that,
const obj={
firstName: 'lokman',
lastName:'hossain'
}
const { firstName,lastName}=obj;
console.log(`first Name:${firstName} last Name:${lastName}`);
N.B:here property name should be same as in object .
What to do if we don't want to match property name as in object .
const {firstName:a,lastName:b}=obj;
console.log(`first name:${a} last name:${lastName}`);
we just define alias of the property name which will be the new const variable.
No comments:
Post a Comment