Destructuring: a way to unpack values from arrays or objects into separate variables.
lets see an example,
//ES5
var data = ['lokman',1989];
console.log(`data ${data}`);
without destructure,
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 .
Rename Variables
const user = {
name: "Lokman",
age: 25
};
const { name: userName, age: userAge } = user;
console.log(userName); // Lokman
console.log(userAge); // 25Function Parameter Destructuring
const user = {
name: "Lokman",
age: 25
};
function printUser({ name, age }) {
console.log(name, age);
}
printUser(user);
No comments:
Post a Comment