Skip to content
This repository was archived by the owner on Feb 19, 2018. It is now read-only.
This repository was archived by the owner on Feb 19, 2018. It is now read-only.

CS2 Discussion: Output: Destructuring #69

Closed
@GeoffreyBooth

Description

@GeoffreyBooth

Building off of #18, we should consider changing CoffeeScript’s destructuring output from the current ES3 to ESNext syntax. So this:

numbers = [1, 2, 3]
pairs = { a: 1, b: 2, c: 3 }

[one, two, three] = numbers
{one, two, three} = pairs

foo = ->
  [@a, @b, @c] = numbers
  {@a, @b, @c} = pairs
  return

which currently compiles to this:

var foo, numbers, one, pairs, three, two;

numbers = [1, 2, 3];

pairs = {
  a: 1,
  b: 2,
  c: 3
};

one = numbers[0], two = numbers[1], three = numbers[2];

one = pairs.one, two = pairs.two, three = pairs.three;

foo = function() {
  this.a = numbers[0], this.b = numbers[1], this.c = numbers[2];
  this.a = pairs.a, this.b = pairs.b, this.c = pairs.c;
};

would instead compile to this (?):

var foo, numbers, one, pairs, three, two;

numbers = [1, 2, 3];

pairs = {
  a: 1,
  b: 2,
  c: 3
};

[one, two, three] = numbers;
({one, two, three} = pairs);

foo = function() {
  [this.a, this.b, this.c] = numbers;
  ({a: this.a, b: this.b, c: this.c} = pairs);
};

The array destructuring, as you can see here, is pretty straightforward; but the object destructuring presents issues. First, if we’re not declaring the variable at the same time (as we never do in CoffeeScript, hence the var line of declarations at the top of each scope) then we need to wrap the destructuring assignment in parentheses, per MDN. And if the target variable is attached to this, we need to use the “assigning to new variable names” shortcut to destructure into our intended destination variable, unless people have a better suggestion for how to handle this.

There’s also the question of whether this is worth the effort. The current output is already rather readable, so the gains aren’t great. Destructuring, whether in CS or ES, is just a time-saver; anything you can do with destructuring you can also already do in more verbose variable assignment, so there’s no compatibility need for us to change anything. If anything, the lack of need behooves us to make sure that if we make this change, it is done in a fully backward compatible way.

Edit: Fixed destructuring object with this per @lydell’s correction.

Metadata

Metadata

Assignees

No one assigned

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions