mizech mizech - 1 month ago 6
Javascript Question

JavaScript Pattern: Is this a valid way of assigning multiple values to an array?

I have seen that pattern on CodeReview:
http://codereview.stackexchange.com/questions/144954/generate-a-table-with-random-numbers

The last function "shuffeledArray".

The following code is used to assign multiple values to an array in one operation:



var demo = [];

[demo[0], demo[1], demo[2]] = [2, 4, 8];

console.log(demo);





It works.

But I ask myself:

Shall one use these technique? Or are there disadvantages?

Answer

It's just a poor example of a useful feature: Destructuring assignment.

A better example makes the usefulness of destructuring assignment a bit more apparent. Consider the case where a function needs to return more than one return value. Normally, we return an object or an array. With destructuring assignment, we can consume that return value with individual variables:

As an object:

function minMax(a) {
  let min = a[0], max = a[0];
  a.forEach(entry => {
    if (min > entry) {
      min = entry;
    }
    if (max < entry) {
      max = entry;
    }
  });
  return {min, max};
}

let {min, max} = minMax([2, 4, 8]);
console.log(min, max);

As an array:

function minMax(a) {
  let min = a[0], max = a[0];
  a.forEach(entry => {
    if (min > entry) {
      min = entry;
    }
    if (max < entry) {
      max = entry;
    }
  });
  return [min, max];
}

let [min, max] = minMax([2, 4, 8]);
console.log(min, max);

Destructuring with objects is particularly useful, for instance, when dealing with modules. Suppose a module exports a whole slew of things, of which you need only foo and bar:

import {foo, bar} from "./module";

With regard to the browser support argument for not using it: That's what transpiling is for. I've been happily using ES2015 in projects meant for browsers all the way back to IE9 for over two years (yes, before the spec was finalized), thanks to transpiling.

Comments