Lesson 6 of 8
Destructuring objects and arrays
- 13 min
- 6 checks
- 3 hints
- Go to task
Goal
Pull values out in a single line
Explanation
Destructuring pulls values out of an object or an array and puts them into variables in a single line. You write const { name, city } = user instead of two lines that each repeat user., and you write const [first] = list to take from an array by position rather than by name.
It comes with two handy extras. The first is a default value, like { city = 'Unknown' }, which is used when the property is undefined but not when it's null. The second is renaming, like { posts: count }, for when the property's name doesn't suit you. The most useful place for destructuring is a function's parameters, because you can tell what the function needs just by reading the line that defines it.
Watch out for a common mistake: destructuring a nested object that doesn't exist crashes the program. For example, { stats: { posts } } throws a TypeError for a user who has no stats. The fix is to give that level itself a default value, like this: { stats: { posts } = {} }.
Your task
Rewrite describe so it destructures its parameter right in the line that defines it. Take city with the default value "Unknown", and take posts from inside stats under the name count, with a default of 0 even when there's no stats at all. Then get the first name by destructuring the array that name.split(' ') returns.
Checks
6 checks- With complete data you get the first name, the city and the count
- A missing city becomes "Unknown"
- A missing stats object doesn't throw an error and gives 0
- A stats object without posts gives 0
- The parameter is destructured in the function's definition line
- The first name comes from array destructuring