Lesson 6 of 8

Destructuring objects and arrays

Goal

Pull values out in a single line

01

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 } = {} }.

02

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
  1. With complete data you get the first name, the city and the count
  2. A missing city becomes "Unknown"
  3. A missing stats object doesn't throw an error and gives 0
  4. A stats object without posts gives 0
  5. The parameter is destructured in the function's definition line
  6. The first name comes from array destructuring
03

Hints

0/3
Track lessons0 of 8 done

Work with data, functions and operations that take time, and build up to an interface that creates its elements from data.

Intermediate level, 8 lessons, 2 hours in total.

index.html
Preview
index.html100%
–/6

Press “Run and check” to grade your code.

6 checks listed under “Your task”.

Track lessons0 of 8 done

Work with data, functions and operations that take time, and build up to an interface that creates its elements from data.

Intermediate level, 8 lessons, 2 hours in total.