Thursday, April 20, 2017

ES6 Structuring and Destructuring

JavaScript ES6 contains a great new feature called  "Destructuring Assignment". It is great because among other things it allows you to do things like:

  [a, b] = [b, a];

In other words it allows you to swap the values of two variables without the help of any extra temporary variable!

More typically and usefully Destructuring Assignment can be used to de-struct an object saving values of its chosen properties into individual variables:

  var {a, b} = {a: 1, b: 2}
  // a -> 1, b -> 2


Another great ES6 feature is called "Shorthand property name". That allows you to create objects out of variables so that the  name of the variable  becomes the property-key and  value of the variable becomes the value (of the property). Like this:

  var ding = 55;
  var myOb = {ding};
  ok (myOb.ding === 55);


What may not be immediately obvious is that Destructuring Assignment and Shorthand Property Name are two sides of the same coin.  In fact I think Shorthand Property Name could and should be called simply "Structuring".

Here's an example of how structuring followed by destructuring gives us back the original (like flipping a coin):

  var ding           = {};
  var originalDing   = ding;
  var myOb           = {ding};   // STRUCTURING
  ding = "forget about it";
  ok  (ding !== originalDing);
  var {ding}         = myOb ;    // DE-STRUCTURING
  ok  (ding === originalDing);


(Note, "ok()" is my simple assertion utility-function)

LINKS:


Copyright © 2017 Panu Viljamaa. All rights reserved 

1 comment:

  1. Array destructuring can be used to make Lisp-like list-processing easy in ES6. I can write:

    var [car, ...cdr] = [1,2,3];
    // car -> 1, cdr -> [2,3]

    However what I wish I could also write is:

    var [ ...woLast, last ] = [1,2,3];
    // woLast -> [1,2], last -> 3

    It seems there is no convenient way to access the last element of an array in JavaScript, is there? We need to write: anArray[anArray.length-1] which is rather clumsy if you need to do it often.

    ReplyDelete