Restructuring Assignment In Es6 Classes

Posted on by Arak

The destructuring assignment syntax is a JavaScript expression that makes it possible to unpack values from arrays, or properties from objects, into distinct variables.

The source for this interactive example is stored in a GitHub repository. If you'd like to contribute to the interactive examples project, please clone https://github.com/mdn/interactive-examples and send us a pull request.

Syntax

var a, b, rest; [a, b] = [10, 20]; console.log(a); // 10 console.log(b); // 20 [a, b, ...rest] = [10, 20, 30, 40, 50]; console.log(a); // 10 console.log(b); // 20 console.log(rest); // [30, 40, 50] ({ a, b } = { a: 10, b: 20 }); console.log(a); // 10 console.log(b); // 20 // Stage 3 proposal ({a, b, ...rest} = {a: 10, b: 20, c: 30, d: 40}); console.log(a); // 10 console.log(b); // 20 console.log(rest); //{c: 30, d: 40}

Description

The object and array literal expressions provide an easy way to create ad hoc packages of data.

var x = [1, 2, 3, 4, 5];

The destructuring assignment uses similar syntax, but on the left-hand side of the assignment to define what values to unpack from the sourced variable.

var x = [1, 2, 3, 4, 5]; var [y, z] = x; console.log(y); // 1 console.log(z); // 2

This capability is similar to features present in languages such as Perl and Python.

Array destructuring

Basic variable assignment

var foo = ['one', 'two', 'three']; var [one, two, three] = foo; console.log(one); // "one" console.log(two); // "two" console.log(three); // "three"

Assignment separate from declaration

A variable can be assigned its value via destructuring separate from the variable's declaration.

var a, b; [a, b] = [1, 2]; console.log(a); // 1 console.log(b); // 2

Default values

A variable can be assigned a default, in the case that the value unpacked from the array is .

var a, b; [a=5, b=7] = [1]; console.log(a); // 1 console.log(b); // 7

Swapping variables

Two variables values can be swapped in one destructuring expression.

Without destructuring assignment, swapping two values requires a temporary variable (or, in some low-level languages, the XOR-swap trick).

var a = 1; var b = 3; [a, b] = [b, a]; console.log(a); // 3 console.log(b); // 1

Parsing an array returned from a function

It's always been possible to return an array from a function. Destructuring can make working with an array return value more concise.

In this example, returns the values as its output, which can be parsed in a single line with destructuring.

function f() { return [1, 2]; } var a, b; [a, b] = f(); console.log(a); // 1 console.log(b); // 2

Ignoring some returned values

You can ignore return values that you're not interested in:

function f() { return [1, 2, 3]; } var [a, , b] = f(); console.log(a); // 1 console.log(b); // 3

You can also ignore all returned values:

[,,] = f();

Assigning the rest of an array to a variable

When destructuring an array, you can unpack and assign the remaining part of it to a variable using the rest pattern:

var [a, ...b] = [1, 2, 3]; console.log(a); // 1 console.log(b); // [2, 3]

Note that a will be thrown if a trailing comma is used on the left-hand side with a rest element:

var [a, ...b,] = [1, 2, 3]; // SyntaxError: rest element may not have a trailing comma

Unpacking values from a regular expression match

When the regular expression method finds a match, it returns an array containing first the entire matched portion of the string and then the portions of the string that matched each parenthesized group in the regular expression. Destructuring assignment allows you to unpack the parts out of this array easily, ignoring the full match if it is not needed.

function parseProtocol(url) { var parsedURL = /^(\w+)\:\/\/([^\/]+)\/(.*)$/.exec(url); if (!parsedURL) { return false; } console.log(parsedURL); // ["https://developer.mozilla.org/en-US/Web/JavaScript", "https", "developer.mozilla.org", "en-US/Web/JavaScript"] var [, protocol, fullhost, fullpath] = parsedURL; return protocol; } console.log(parseProtocol('https://developer.mozilla.org/en-US/Web/JavaScript')); // "https"

Object destructuring

Basic assignment

var o = {p: 42, q: true}; var {p, q} = o; console.log(p); // 42 console.log(q); // true

Assignment without declaration

A variable can be assigned its value with destructuring separate from its declaration.

var a, b; ({a, b} = {a: 1, b: 2});

The round braces  around the assignment statement is required syntax when using object literal destructuring assignment without a declaration.

is not valid stand-alone syntax, as the on the left-hand side is considered a block and not an object literal.

However, is valid, as is

Assigning to new variable names

A property can be unpacked from an object and assigned to a variable with a different name than the object property.

var o = {p: 42, q: true}; var {p: foo, q: bar} = o; console.log(foo); // 42 console.log(bar); // true

Default values

A variable can be assigned a default, in the case that the value unpacked from the object is .

var {a = 10, b = 5} = {a: 3}; console.log(a); // 3 console.log(b); // 5

Assigning to new variables names and providing default values

A property can be both 1) unpacked from an object and assigned to a variable with a different name and 2) assigned a default value in case the unpacked value is .

var {a:aa = 10, b:bb = 5} = {a: 3}; console.log(aa); // 3 console.log(bb); // 5

Setting a function parameter's default value

ES5 version

function drawES5Chart(options) { options = options === undefined ? {} : options; var size = options.size === undefined ? 'big' : options.size; var cords = options.cords === undefined ? {x: 0, y: 0} : options.cords; var radius = options.radius === undefined ? 25 : options.radius; console.log(size, cords, radius); // now finally do some chart drawing } drawES5Chart({ cords: {x: 18, y: 30}, radius: 30 });

ES2015 version

function drawES2015Chart({size = 'big', cords = {x: 0, y: 0}, radius = 25} = {}) { console.log(size, cords, radius); // do some chart drawing } drawES2015Chart({ cords: {x: 18, y: 30}, radius: 30 });

In the function signature for above, the destructured left-hand side is assigned to an empty object literal on the right-hand side: . You could have also written the function without the right-hand side assignment. However, if you leave out the right-hand side assignment, the function will look for at least one argument to be supplied when invoked, whereas in its current form, you can simply call without supplying any parameters. The current design is useful if you want to be able to call the function without supplying any parameters, the other can be useful when you want to ensure an object is passed to the function.

Nested object and array destructuring

var metadata = { title: 'Scratchpad', translations: [ { locale: 'de', localization_tags: [], last_edit: '2014-04-14T08:43:37', url: '/de/docs/Tools/Scratchpad', title: 'JavaScript-Umgebung' } ], url: '/en-US/docs/Tools/Scratchpad' }; var {title: englishTitle, translations: [{title: localeTitle}]} = metadata; console.log(englishTitle); // "Scratchpad" console.log(localeTitle); // "JavaScript-Umgebung"

For of iteration and destructuring

var people = [ { name: 'Mike Smith', family: { mother: 'Jane Smith', father: 'Harry Smith', sister: 'Samantha Smith' }, age: 35 }, { name: 'Tom Jones', family: { mother: 'Norah Jones', father: 'Richard Jones', brother: 'Howard Jones' }, age: 25 } ]; for (var {name: n, family: {father: f}} of people) { console.log('Name: ' + n + ', Father: ' + f); } // "Name: Mike Smith, Father: Harry Smith" // "Name: Tom Jones, Father: Richard Jones"

Unpacking fields from objects passed as function parameter

function userId({id}) { return id; } function whois({displayName, fullName: {firstName: name}}) { console.log(displayName + ' is ' + name); } var user = { id: 42, displayName: 'jdoe', fullName: { firstName: 'John', lastName: 'Doe' } }; console.log('userId: ' + userId(user)); // "userId: 42" whois(user); // "jdoe is John"

This unpacks the , and from the user object and prints them.

Computed object property names and destructuring

Computed property names, like on object literals, can be used with destructuring.

let key = 'z'; let {[key]: foo} = {z: 'bar'}; console.log(foo); // "bar"

Rest in Object Destructuring

The Rest/Spread Properties for ECMAScript proposal (stage 3) adds the rest syntax to destructuring. Rest properties collect the remaining own enumerable property keys that are not already picked off by the destructuring pattern.

let {a, b, ...rest} = {a: 10, b: 20, c: 30, d: 40} a; // 10 b; // 20 rest; // { c: 30, d: 40 }

Invalid JavaScript identifier as a property name

Destructuring can be used with property names that are not valid JavaScript identifiers by providing an alternative identifer that is valid.

const foo = { 'fizz-buzz': true }; const { 'fizz-buzz': fizzBuzz } = foo; console.log(fizzBuzz); // "true"

Specifications

Browser compatibility

The compatibility table on this page is generated from structured data. If you'd like to contribute to the data, please check out https://github.com/mdn/browser-compat-data and send us a pull request.

FeatureChromeEdgeFirefoxInternet ExplorerOperaSafari
Basic support4914411 No Yes8
Computed property names491434 No Yes No
Rest in arrays4914234 No Yes No
Rest in objects60 No55 No Yes No
FeatureAndroid webviewChrome for AndroidEdge mobileFirefox for AndroidOpera AndroidiOS SafariSamsung Internet
Basic support494914411 Yes8 ?
Computed property names49491434 Yes No ?
Rest in arrays494914234 Yes No ?
Rest in objects6060 No55 Yes No ?

1. Firefox provided a non-standard destructuring implementation from Firefox 2 to 40.

2. From version 14: this feature is behind the preference.

DesktopMobileServer
ChromeEdgeFirefoxInternet ExplorerOperaSafariAndroid webviewChrome for AndroidEdge MobileFirefox for AndroidOpera for AndroidiOS SafariSamsung InternetNode.js
Basic supportFull support 49Full support 14Full support 41

Notes

Full support 41

Notes

Notes Firefox provided a non-standard destructuring implementation from Firefox 2 to 40.
No support NoFull support YesFull support 8Full support 49Full support 49Full support 14Full support 41

Notes

Full support 41

Notes

Notes Firefox provided a non-standard destructuring implementation from Firefox 2 to 40.
Full support YesFull support 8 ? Full support Yes
Computed property namesFull support 49Full support 14Full support 34No support NoFull support YesNo support NoFull support 49Full support 49Full support 14Full support 34Full support YesNo support No ? Full support Yes
Rest in arraysFull support 49Full support 14

Disabled

Full support 14

Disabled

Disabled From version 14: this feature is behind the preference.
Full support 34No support NoFull support YesNo support NoFull support 49Full support 49Full support 14

Disabled

Full support 14

Disabled

Disabled From version 14: this feature is behind the preference.
Full support 34Full support YesNo support No ? Full support Yes
Rest in objects

Experimental

Full support 60No support NoFull support 55No support NoFull support YesNo support NoFull support 60Full support 60No support NoFull support 55Full support YesNo support No ? Full support Yes

Legend

Full support
Full support
No support
No support
Compatibility unknown
Compatibility unknown
Experimental. Expect behavior to change in the future.
Experimental. Expect behavior to change in the future.
See implementation notes.
See implementation notes.
User must explicitly enable this feature.
User must explicitly enable this feature.

See also

ES6 In Depth is a series on new features being added to the JavaScript programming language in the 6th Edition of the ECMAScript standard, ES6 for short.

Editor’s note: An earlier version of today’s post, by Firefox Developer Tools engineer Nick Fitzgerald, originally appeared on Nick’s blog as Destructuring Assignment in ES6.

What is destructuring assignment?

Destructuring assignment allows you to assign the properties of an array or object to variables using syntax that looks similar to array or object literals. This syntax can be extremely terse, while still exhibiting more clarity than the traditional property access.

Without destructuring assignment, you might access the first three items in an array like this:

With destructuring assignment, the equivalent code becomes more concise and readable:

SpiderMonkey (Firefox’s JavaScript engine) already has support for most of destructuring, but not quite all of it. Track SpiderMonkey’s destructuring (and general ES6) support in bug 694100.

Destructuring arrays and iterables

We already saw one example of destructuring assignment on an array above. The general form of the syntax is:

This will just assign variable1 through variableN to the corresponding item in the array. If you want to declare your variables at the same time, you can add a , , or in front of the assignment:

In fact, is a misnomer since you can nest patterns as deep as you would like:

Furthermore, you can skip over items in the array being destructured:

var [,,third] = ["foo", "bar", "baz"]; console.log(third); // "baz"

And you can capture all trailing items in an array with a “rest” pattern:

When you access items in the array that are out of bounds or don’t exist, you get the same result you would by indexing: .

Note that destructuring assignment with an array assignment pattern also works for any iterable:

Destructuring objects

Destructuring on objects lets you bind variables to different properties of an object. You specify the property being bound, followed by the variable you are binding its value to.

There is a helpful syntactical shortcut for when the property and variable names are the same:

And just like destructuring on arrays, you can nest and combine further destructuring:

When you destructure on properties that are not defined, you get :

One potential gotcha you should be aware of is when you are using destructuring on an object to assign variables, but not to declare them (when there is no , , or ):

This happens because the JavaScript grammar tells the engine to parse any statement starting with as a block statement (for example, is a valid block statement). The solution is to either wrap the whole expression in parentheses:

Destructuring values that are not an object, array, or iterable

When you try to use destructuring on or , you get a type error:

However, you can destructure on other primitive types such as booleans, numbers, and strings, and get :

This may come unexpected, but upon further examination the reason turns out to be simple. When using an object assignment pattern, the value being destructured is required to be coercible to an . Most types can be converted to an object, but and may not be converted. When using an array assignment pattern, the value must have an iterator.

Default values

You can also provide default values for when the property you are destructuring is not defined:

(Editor’s note: This feature is currently implemented in Firefox only for the first two cases, not the third. See bug 932080.)

Practical applications of destructuring

Function parameter definitions

As developers, we can often expose more ergonomic APIs by accepting a single object with multiple properties as a parameter instead of forcing our API consumers to remember the order of many individual parameters. We can use destructuring to avoid repeating this single parameter object whenever we want to reference one of its properties:

This is a simplified snippet of real world code from the Firefox DevTools JavaScript debugger (which is also implemented in JavaScript—yo dawg). We have found this pattern particularly pleasing.

Configuration object parameters

Expanding on the previous example, we can also give default values to the properties of the objects we are destructuring. This is particularly helpful when we have an object that is meant to provide configuration and many of the object’s properties already have sensible defaults. For example, jQuery’s function takes a configuration object as its second parameter, and could be rewritten like this:

This avoids repeating for each property of the configuration object.

(Editor’s note: Unfortunately, default values within object shorthand syntax still aren’t implemented in Firefox. I know, we’ve had several paragraphs to work on it since that earlier note. See bug 932080 for the latest updates.)

With the ES6 iteration protocol

ECMAScript 6 also defines an iteration protocol, which we talked about earlier in this series. When you iterate over s (an ES6 addition to the standard library), you get a series of pairs. We can destructure this pair to get easy access to both the key and the value:

Iterate over only the keys:

Or iterate over only the values:

Multiple return values

Although multiple return values aren’t baked into the language proper, they don’t need to be because you can return an array and destructure the result:

Alternatively, you can use an object as the container and name the returned values:

Both of these patterns end up much better than holding onto the temporary container:

Or using continuation passing style:

Importing names from a CommonJS module

Not using ES6 modules yet? Still using CommonJS modules? No problem! When importing some CommonJS module X, it is fairly common that module X exports more functions than you actually intend to use. With destructuring, you can be explicit about which parts of a given module you’d like to use and avoid cluttering your namespace:

(And if you do use ES6 modules, you know that a similar syntax is available in declarations.)

Conclusion

So, as you can see, destructuring is useful in many individually small cases. At Mozilla we’ve had a lot of experience with it. Lars Hansen introduced JS destructuring in Opera ten years ago, and Brendan Eich added support to Firefox a bit later. It shipped in Firefox 2. So we know that destructuring sneaks into your everyday use of the language, quietly making your code a bit shorter and cleaner all over the place.

Five weeks ago, we said that ES6 would change the way you write JavaScript. It is this sort of feature we had particularly in mind: simple improvements that can be learned one at a time. Taken together, they will end up affecting every project you work on. Revolution by way of evolution.

Updating destructuring to comply with ES6 has been a team effort. Special thanks to Tooru Fujisawa (arai) and Arpad Borsos (Swatinem) for their excellent contributions.

Support for destructuring is under development for Chrome, and other browsers will undoubtedly add support in time. For now, you’ll need to use Babel or Traceur if you want to use destructuring on the Web.


Thanks again to Nick Fitzgerald for this week’s post.

Next week, we’ll cover a feature that is nothing more or less than a slightly shorter way to write something JS already has—something that has been one of the fundamental building blocks of the language all along. Will you care? Is slightly shorter syntax something you can get excited about? I confidently predict the answer is yes, but don’t take my word for it. Join us next week and find out, as we look at ES6 arrow functions in depth.

Jason Orendorff

ES6 In Depth editor

Categories: 1

0 Replies to “Restructuring Assignment In Es6 Classes”

Leave a comment

L'indirizzo email non verrà pubblicato. I campi obbligatori sono contrassegnati *