-
Notifications
You must be signed in to change notification settings - Fork 4
CS2 Discussion: Features: Block assignment operator #58
Description
Splitting off from #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); // undefinedThis 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 = 1means, “declareaat the top of this function scope usingvar, and assignahere with the value of1.”a := 1would mean, “declareaat the top of this block scope usinglet, and assignahere with the value of1.”
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 := 3would 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 #35. Thanks.