JavaScript Intermediate: Data, the DOM and Events
Objects, Destructuring and Spread
In this lesson you will
- Unpack objects and arrays with destructuring
- Copy and merge with the spread operator
- Read missing data safely with optional chaining and nullish coalescing
Introduction
Modern JavaScript has a handful of shortcuts that make working with objects and arrays much shorter and safer. You will see them in almost every codebase.
Destructuring objects
Instead of pulling out properties one by one, unpack them in one line.
The variable names must match the property names. Use city: town to give a different name.
Defaults and function parameters
You can set defaults, and destructure right in a function's parameters.
Quick quiz
What does const { a, b } = obj; do?
Destructuring arrays
For arrays, unpack by position.
...rest collects the remaining items. The last example swaps two variables.
Spread: copy and merge
The three dots ... also spread an array or object into another.
Spread makes a shallow copy. The original object is left untouched, which is a good habit: create new data instead of changing old data. Properties that come later win, as age shows.
Quick quiz
What does { ...base, age: 9 } produce?
Optional chaining and nullish coalescing
Reading a property of undefined causes an error. ?. stops safely and returns undefined instead. ?? gives a fallback only when the value is null or undefined.
Note the difference: || replaces any falsy value (including 0), while ?? only replaces null and undefined.
JSON
JSON is a text format for data, used by almost every web service. Two functions convert between objects and JSON text.
Quick quiz
Which function turns an object into a JSON string?
Try it yourself
Write a function fullName({ first, last, title }) that returns the title (if there is one), the first name and the last name. Use a default for title of an empty string, and test it.
Summary
- Destructuring unpacks objects and arrays into variables.
- Spread
...copies and merges without changing the original. ?.reads safely, and??supplies a fallback fornullorundefined.JSON.stringifyandJSON.parseconvert between data and text.
Lesson complete
+20 XP
Nice work. Keep going while it is fresh.
Sources and further reading