JAVASCRIPT / CHAPTER 07

Destructuring, defaults, and rest parameters

Intermediate

Separate absent values from valid explicit values.

By the end of this chapter

  • Read array and object patterns
  • Apply defaults only to undefined
  • Collect remaining arguments predictably

The idea

Destructuring gives local names to positions or properties without changing the source. An object pattern may rename a property; an array pattern uses positions. A default expression runs when the selected value is undefined, including a missing property. It does not replace null, zero, or false. This distinction matters when a caller intentionally supplies an empty or disabled setting.

Rest parameters collect remaining arguments into an array. They work well when a function naturally accepts a variable number of values, but they do not validate those values. Destructured function parameters also need an outer default if calling with no argument should be allowed. An outer empty-object default handles undefined; passing null still cannot be destructured as an object.

JavaScript example
function describe({size = 8, label: name = "item"} = {}) {
  return name + ":" + size;
}
console.log(describe({size: 0}));
console.log(describe());
Result
item:0
item:8

The property default preserves zero. The parameter default supplies an object when the argument is omitted.

Try it yourself

Write a function accepting an optional options object with an optional prefix and any number of numeric values.

Use your own editor for this exercise. Runnable challenges on CodeQuest are available for JavaScript, Python, and SQL.

Open JavaScript coding challenges

CHECK YOUR UNDERSTANDING

Chapter checkpoint

What is n after this pattern?
const {n = 9} = {n: null};