Using a Destructuring Assignment to Simplify Code
Problem
You want to assign array element values to several variables, but you really don’t want to have assign each, individually.
Solution
Use ECMAScript 6’s destructuring assignment to simplify array assignment:
var stateValues = [459, 144, 96, 34, 0, 14]; var [Arizona, Missouri, Idaho, Nebraska, Texas, Minnesota] = stateValues; console.log(Missouri); // 144
EXPLAIN
In the solution, variables are declared and instantiated with values in an Array, starting with the Array index at position zero. If the number of variables is less than the array elements, they’re assigned the element values up until all variables have been assigned. If there are more variables than array elements, the unmatched variables are created, but they’re set to undefined.
The destructuring assignment is less a new feature in ECMAScript 6, and more an en‐ hancement of existing functionality. It’s not necessary functionality, as it’s not providing access to functionality we’ve not had and can’t emulate. It’s an improvement in the language that will, according to the specification, “Allow for destructuring of arrays and objects using syntax that mirrors array and object initialisers.”
Unfortunately, implementation of the functionality is extremely limited, and there is no shim that I know of that can emulate it. However, things change quickly in the world of JavaScript, and it’s good to be aware of what’s coming down the road.
Harmony Flags and Using Traceur
V8 JavaScript Engine developers have signaled future implementation of destructuring
assignment, which means the capability will also be available in Node.js, as well as
browsers like Chrome and Opera (in addition to existing support in Firefox).
Enabling the newest, latest ECMAScript features is typically off by default in most
browsers and environments. However, you can signal that you want to enable support
for newer features in some of the environments.
In Chrome and Opera, you can enable ES 6 feature support by accessing the URL
chrome://flags. This opens up the flags page, where you can search for a flag labeled
Experimental JavaScript and enable it. Note that this can add to the instability of your
JavaScript applications.
In addition to enabling ES 6 support in browsers and Node, Google created Traceur, an
application that takes ECMAScript.next code and transpiles (translates and compiles)
it into ECMAScript.current code, which should be executable in all modern environ‐
ments.
An example of using Traceur is the following, the results of using the application
on the solution code:
$traceurRuntime.ModuleStore.getAnonymousModule(function() { "use strict"; var stateValues = [459, 144, 96, 34, 0, 14]; var $__3 = stateValues, Arizona = $__3[0], Missouri = $__3[1], Idaho = $__3[2], Nebraska = $__3[3], Texas = $__3[4], Minnesota = $__3[5]; console.log(Missouri); return {}; });
No comments:
Post a Comment