Object destructuring

First of all, let's see an example of object destructuring:

1. let user = {name:'Sunny', interests:['Traveling', 'Swimming']};
2. let {name, interests, tasks} = user;
3. console.log(name); // Sunny
4. console.log(interests); // ["Traveling", "Swimming"]
5. console.log(tasks); // undefined

As you can see, the name and interests variables defined in line 2 pick up the values of the properties with the same name in the user object. And the tasks variable doesn't have a matching property in the user object. Its value remains as undefined. You can avoid this by giving it a default value, like this:

let {name, interests, tasks=[]} = user;
console.log(tasks) // []

Another thing you can do with object destructuring is that you can choose a different variable name. In the following example, we pick the value of the name property of the user object and assign it to the firstName variable:

let {name: firstName} = user;
console.log(firstName) // Sunny
..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.144.30.62