W3docs

JavaScript Destructuring Assignment

Learn JavaScript destructuring assignment: unpack arrays and objects, set defaults, rename variables, use nested and rest patterns.

Understanding Destructuring in JavaScript

Destructuring assignment is a syntax that lets you unpack values from arrays or properties from objects into distinct variables in a single, compact statement. Introduced in ES6 (ES2015), it replaces repetitive one-property-at-a-time access and makes code that works with structured data far easier to read.

Without destructuring you write code like this:

javascript— editable

With destructuring, the same intent fits on one line. The rest of this chapter covers the array and object forms, default values, renaming, nested patterns, the rest pattern, swapping variables, function-parameter destructuring, and the common ({ a } = {}) gotcha.

Array Destructuring: Unpacking Elements

Array destructuring assigns array elements to distinct variables based on their position (index). The variables on the left mirror the order of the values on the right. It is especially handy for function return values and iterating over key/value pairs.

Basic Array Destructuring

javascript— editable

A variable with no matching element becomes undefined, which is where default values come in (below).

Skipping Elements and Default Values

Leave a "hole" (an empty slot between commas) to skip elements you don't need. Add = value to give a variable a fallback that is used only when the unpacked value is undefined:

javascript— editable

Because destructuring works on any iterable, it pairs naturally with the rest pattern to collect leftover items:

javascript— editable

Object Destructuring: Extracting Properties

Object destructuring provides a convenient way to extract multiple properties from objects. This technique can enhance the management of configuration objects or data processing from complex structures.

Simple Object Destructuring

javascript— editable

Unlike arrays, object destructuring matches by property name, not position, so the order of the keys in the pattern does not matter.

Renaming Variables and Setting Defaults

Use the propertyName: newName syntax to assign a property to a variable with a different name — useful when the property name clashes with an existing variable or isn't a valid identifier. Defaults work the same as with arrays:

javascript— editable

You can rename and supply a default at the same time with property: newName = default:

javascript— editable

Advanced Destructuring Techniques

Advanced destructuring encompasses nested structures and the use of the rest parameter for aggregating remaining properties or elements.

Nested Destructuring

Patterns can be nested to reach deep into objects and arrays at once. The pattern's shape simply mirrors the data's shape:

javascript— editable

Note that size: and items: here are not variables — they are just the path into the structure. Only width, height, item1, and item2 become variables.

Using the Rest Pattern

The rest pattern (...name) gathers all the remaining, un-destructured properties into a new object. Read more in Rest Parameters and Spread Syntax:

javascript— editable

Practical Applications of Destructuring

Destructuring proves invaluable in various practical applications, such as:

  1. Swapping Variables: Simplifies the process of exchanging values between variables.
  2. Function Parameter Management: Enhances the handling of multiple parameters, particularly for functions with numerous optional parameters.

Swapping Variables

Destructuring swaps two values without a temporary variable. The right-hand array is built first, then unpacked into the variables on the left:

javascript— editable

Function Parameters

Destructuring a parameter lets a function accept an "options object" and pull out named settings with sensible defaults — far cleaner than a long, order-sensitive parameter list. The trailing = {} is what lets the caller omit the argument entirely:

javascript— editable

Learn more about parameters in the JavaScript Functions chapter.

The ({ a } = {}) Gotcha

When you destructure an existing variable (not in a const/let declaration), you must wrap the statement in parentheses. Otherwise JavaScript reads the leading { as the start of a code block, not an object pattern, and throws a syntax error:

javascript— editable

The parentheses are only needed for object destructuring into already-declared variables. Array destructuring ([a, b] = [1, 2]) does not have this problem because [ never begins a statement block.

A related trap: when both the variable and its default come from a possibly-missing source, give the whole parameter a default of {} (as in drawChart above). Without it, calling the function with no argument throws, because you cannot read a property from undefined.

Conclusion

JavaScript destructuring is a powerful feature that offers more readable, concise, and maintainable code. By adopting this approach, developers can efficiently handle data extraction from arrays and objects, leading to cleaner and more effective code structures.

Practice

Practice
What are the uses of destructuring assignment in JavaScript according to the information on the provided webpage?
What are the uses of destructuring assignment in JavaScript according to the information on the provided webpage?
Was this page helpful?