Skip to content

CS2 Discussion: Features: Block assignment operator #4951

Closed
@coffeescriptbot

Description

@coffeescriptbot

From @GeoffreyBooth on 2016-12-05 07:21

Splitting off from coffeescript6/discuss#35, this proposal is for just one new operator: :=, the block assignment operator. So the great advantage of let/const is its block-scoping, i.e.:

let a = 1;
if (true) {
  let b = 2;
}
console.log(b); // undefined

This is a genuinely new feature added in ES2015, and a great improvement over var, which explains why let and const have become popular features. This block scoping that let and const each offer is probably something that CoffeeScript should have, separate from the feature of const that means “throw an error on reassignment.”

The new operator would behave similarly to =:

  • a = 1 means, “declare a at the top of this function scope using var, and assign a here with the value of 1.”
  • a := 1 would mean, “declare a at the top of this block scope using let, and assign a here with the value of 1.”

let has the same issue as var, in that its declaration is hoisted to its entire scope (what MDN refers to as the temporal dead zone), so let declarations should be grouped together at the top of their block scope similar to how var declarations are currently grouped at the top of their function scope.

What about const? Well, there’s really no reason we need it. It protects against reassignment of variables, and that’s all it does. Per this comment, it probably has no performance benefit in runtimes; and since const reassignments can be caught by transpilers (whether CoffeeScript or Babel) such reassignments are in practice usually caught at compile time, not run time. If we decide we want to provide a way to output const, for full expressibility of ES2015 and for this protection against reassignment, that could be a separate feature added later.

So this CoffeeScript:

a = 1
b := 2

if (yes)
  b := 3

would compile into this JavaScript:

var a;
let b;

a = 1;
b = 2;

if (true) {
  let b;

  b = 3;
}

Note about bikeshedding: Please refrain from feedback that says how you prefer the let keyword to :=, or that you prefer some other sequence of characters to :=. Ultimately the keyword or operator chosen is a personal preference decision, and will be made by @jashkenas and whoever implements this. There was plenty of discussion about this on coffeescript6/discuss#35. Thanks.

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions