Hacker Newsnew | past | comments | ask | show | jobs | submitlogin
Destructuring Assignment in ECMAScript 6 (fitzgeraldnick.com)
123 points by mnemonik on Aug 15, 2013 | hide | past | favorite | 56 comments


For anyone interested in trying some of this stuff out (which I highly recommend, because a lot of the new stuff in ES6 is really great), Google has an awesome tool called Traceur [https://github.com/google/traceur-compiler] that will compile ES6 into ES5.

There's also an online version here: [https://github.com/google/traceur-compiler] that's great for quick little experiments. And, as an added bonus, it encodes your script in the URL so you can share it.


Sounds like the Modules implementation isn't ready yet, that's too bad... probably one of the most useful parts of ES6


Yeah. There are some other things that are actually impossible, like WeakMaps. But still, the stuff that exists is pretty awesome.


This, and the short function syntax (that's also already in Firefox stable: "let square = x => x * x") make me very giddy. It's always been possible to write JavaScript in a functional style - but this kind of sugar makes it much much nicer. Things like Traceur will even let us transpile to old-school JS for old browser support, so for a lot of projects we can start using these things real soon.


Combine the two:

    const tail = [, ...xs] => xs;


const tail = ([, ...xs]) => xs;


Ah you can't do the single-param-drop-parens when combined with destructuring? Good to know, thanks Benvie.


For anyone wondering, TypeScript will also include support for this http://typescript.codeplex.com/workitem/15


This is great and allows us to do some slicker functional code:

    function take(num, list) {
      if (num <= 0 || !list || list === []) return [];
      var [head, ...tail] = list;
      return [head].concat(take(num - 1, tail));
    }
It's not as elegant as haskell but it's still nicer than it would be without the new syntax.

Once we have support for tail call optimization, things will get really interesting.


Note: list === [] doesn't do what you expect it to do. It's going to return false all the time because it is comparing the actual objects and not their content.


Ah, yeah, of course. That always threw me off, I've been working too much in other languages.


Use `!list.length` instead.


Yet another great feature heavily inspired from CoffeeScript (and tastefully expanded upon). Well done!

The surprising thing for me is that destructuring _almost_ allows defining default values for function arguments.


Destructuring assignment long predates Coffeescript. According to the Coffeescript docs, they took the syntax from earlier drafts of ES6. Destructuring assignment long predates ES6. Common Lisp had a destructuring-bind macro back in the early 90s, and I'd bet it wasn't a novel invention back then.


And even in JS-land itself, Mozilla introduced destructuring assignment in Javascript 1.7 (alongside iterators, generators, array comprehensions and `let`).

Javascript 1.7 was introduced in Firefox 2, in October 2006.

> I'd bet it wasn't a novel invention back then.

Indeed, ML featured destructuring assignment (which it called "patterns") of tuples and records back in the 70s.


This is the kind of comment that makes me look down on CoffeeScript programmers. I mean, really? You thought Coffeescript invented destructuring bind?


No, I just thought ES6 took the specific syntax they use from CoffeeScript. As other commenters helpfully pointed out, I was wrong.

"CoffeeScript programmers"? Is that a thing?


Default parameter values are also part of ES6.


Default parameter values, ...rest expressions, and modules were all part of ActionScript 3, which was an early implementation of JavaScript Next (then called ECMAScript 4). As I recall, Microsoft and Yahoo! threw a fit about it, and most of the interesting enhancements were shelved.

Glad to see some of the good bits making their way back in. The number of times I've had to do

    function(firstParam, secondParam, thirdParam) {
        if (firstParam.hasOwnProperty('firstParam') {
            var argumentDict = firstParam;
            firstParam = argumentDict['firstParam'];
            secondParam = argumentDict['secondParam'];
            thirdParam = argumentDict['thirdParam'];
        }
        
        firstParam = firstParam || "default value";
        ...
is sickening.


I don't think "threw a fit" is an accurate description. More like, objected to many aspects for technical reasons. And, considering that TC-39 agreed at the Oslo meeting to pursue ES3.1 over ES4, presumably they had a pretty good argument. Brendan Eich's mail sent after the accord[1] has some detail.

1) https://mail.mozilla.org/pipermail/es-discuss/2008-August/00...

(Disclaimer: I work for MS).


Why did Yahoo! care? Why did Yahoo! even have a seat at that table?


Yahoo did and does have a spot at the table because they are a dues-paying member of ECMA. They have as much weight in the committee as any other member (MS, Google, Mozilla, now Facebook, etc.) Presumably Yahoo cares because they have millions of users running JS code.


Also Douglas Crockford worked at Yahoo.


Definitely looking forward to this as well as other new ES6 stuff. There's something else I feel I could use perhaps even more but I haven't seen it in any of the ES* updates. I'm a huge advocate of DRY and it bothers me when I have to code something like:

  var a = objImUsing.prop.someLongName > 5 ? objImUsing.prop.someLongName : whatever;
I can and sometimes just make an extra variable above for a long prop list like this but that adds an extra line. I guess what I would like would be some sort of implied line limited scope:

  var a = objImUsing.prop.someLongName > 5 ? _1 : whatever;
_1 referring to the first mentioned value in the immediate parent statement.


In ES6, you can write more terse immediately invoked function expressions. So you could use

  var a = (prop => prop > 5 ? prop : whatever)(objImUsing.prop.someLongName)
rather than

  var a = (function (prop) { return prop > 5 ? prop : whatever })(objImUsing.prop.someLongName)


In older versions of Firefox, you could write: var a = #1=objImUsing.prop.someLongName > 5 ? #1# : whatever; but it's been killed since Firefox 12: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Shar...


I can see why Brendan Eich is excited to get ES6 out there. It's finally coming back around to parity with Scheme. I'm looking forward to seeing more.


Javascript is the functional programming community's secret weapon! Sure ES6 will add classes, but they're just syntactic sugar. Wrappers around the truly functional language underneath. Everyone is slowly being soothed into using a lisp. And when you realise this, it's the funniest thing to watch!


I'd be hard-pressed to call Javascript a "functional programming language" (whatever that means). Common Lisp also suffers from the same misguided label. In truth we love to mutate state in CL and find lattices of type hierarchies to be burdensome (but a great pool of research for your post-doc).

Scheme is about as close as I'll get to pure-FP languages. I don't seem ES6 going down the "purity," route. And I hope it stays far from the border.

What I was originally referring to though is (if I recall the history of the language) the roots of Javascript -- that it purportedly was a Scheme-like language before becoming what it is today. And by being what it is now has lagged behind in feature-parity to what programmers are used to in other languages whose history isn't tied to the venerable web browser. It just seems to me from the interviews that skirt the topic that Mr. Eich is finally coming back around to introduce what should have been there from the start.

(Updated for clarity)


Of course, it's not Haskell... I'm very aware that Javascript was inspired by Scheme. The lexical scoping for example, is obviously "functional" (indeed, whatever that means). Now they are introducing ways to more easily work with lists. Only thing missing is tail call optimization!


>I'm very aware that Javascript was inspired by Scheme. The lexical scoping for example, is obviously "functional" (indeed, whatever that means).

No it wasn't. That's an urban legend. Eich WANTED to make a Scheme for the browser -- he didn't get a permission to do it, and made Javascript instead, which is actually inspired from other languages like Self.

Nothing functional about Javascript's horribly broken scoping either...

http://journal.stuffwithstuff.com/2013/07/18/javascript-isnt...


You could use const all over the place.


Still doesn't give you immutable data structures though. For example:

    const myArray = [42];
    myArray.push("Oh noes");

    [42, "Oh noes"]


Ugh, you're kidding?

EDIT: checked in Node, yep. That's unfortunate. Can we get a let foo immutable = [1]; or something?

EDIT2: Although this can be implemented in user-land with Object.freeze. Create a function that returns a const that is frozen if it is non-primitive. That should cover it, right?


freeze/seal don't actually provide true immutability in JS. There are cases where a frozen object can still be modified (Date is one of them, IIRC typed arrays are another)


ClojureScript provides truly immutable data structures that compile down to javascript. You can use them from JS:

https://github.com/swannodette/mori


There's nothing "trully functional" about Javascript.

There's not some secret functional language waiting to get out, any more that it is in any other language with first class functions, from Ruby to C#.

http://journal.stuffwithstuff.com/2013/07/18/javascript-isnt...


Javascript isn't functional like Clojure or Haskell ("no side effects"). But it certainly is similar to common LISP regarding frequent use of higher order functions and closures. Some people call that "functional".

Language is more than syntax and set of features. How most people use it is very important, because you will have to interface with others people code, and your code will be interfaced with.

Javascript discourages OO programming because of pathological object creation syntax and unusual inheritance model. In javascript APIs you usually pass literals of a few common types and functions. In C# you pass instances of custom classes. The former is more suited for functional programming than the latter. In javascript you use closures for encapsulation, in C# you use private members.

I don't think I've ever seen "XManager" class in javascript :)


It never had anything to do with Scheme in the first place.

http://journal.stuffwithstuff.com/2013/07/18/javascript-isnt...


I'm on the same page; I never said it was Scheme -- only that in terms of features it's finally starting to catch up with features that Schemes/Lispy-like languages have had for a long, long time.


Still no macros.


PHP has this available as list[1] in a slightly more limited form.

1. http://php.net/list


That was my first thought too. I never really cared for list() in PHP as I find it a somewhat confusing way of assigning variables, and judging by the examples given in the article, I actually preferred the clarity of the less "terse" variable assignments done the old way. Might just be habit though.


Yeah, I never really got it either. Seemed "clever", and I usually try to avoid being too "clever" with code. Readability almost always wins.


I think you found PHP's third good part.

-> https://jeena.net/php-the-good-parts


Good to see, this is one thing I have really missed from Erlang when writing Javascript.


This isn't quite as powerful as full blown pattern matching (which in turn isn't quite as powerful as full blown unification) because you can't branch logic based on whether a pattern matches or not.


Can you elaborate on what "unification" is in this context? The only language that I've used with full-blown pattern matching is Rust, and I'm curious to know what the next step up the ladder is.



Do you happen to know, which is `destructuring-bind`, destructuring or pattern matching?


That's awesome.

Any bets on when we can start using it on the front-end? I'm sure Chrome/FF will pick it up quick once it's finalized, but when will ECMAScript 6 be present in 95% of IE installations? 2020?


You are forgetting all the mobile browsers out there.


With the Destructuring Objects, I was like: WTF, but it all makes sense once you get to the Practical Applications of Destructuring. Nice stuff.


FWIW "objects" destructuring is just about as old as "tuple" destructuring: ML had both in the 70s, which it called "tuple patterns" and "record patterns".


Who needs ML when now we have Javascript?

I never thought I'd hear myself say that. But seriously, this is awesome. Thank you, whomever!


This is nice, reminds me of Scala




Guidelines | FAQ | Lists | API | Security | Legal | Apply to YC | Contact

Search: