CS2 Discussion: Features: Block assignment let and const operators #35
Description
Building off of #1 and this comment, 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 dramatic improvement over var
, and a big reason why let
and const
have become popular features. This block scoping is probably something that CoffeeScript should have, separate from the feature of const
that means “throw an error on reassignment.”
We could have both, via :=
and :==
operators (or whatever two operators people think are best):
a := 1
would mean, “declarea
at the top of this block usinglet
, and on this line assigna
with the value of1
.”a :== 1
would mean, “declare and assigna
on this line usingconst
. If it gets reassigned later, throw an error.”
We don’t necessarily need the second operator, if we don’t care to give the “throw an error on reassignment” feature.
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. const
must be declared and assigned on the same line, so it can’t get moved up.
So this CoffeeScript:
a = 1
b := 2
c :== 3
if (yes)
b := 4
c :== 5
would compile into this JavaScript:
var a;
let b;
a = 1;
b = 2;
const c = 3;
if (true) {
let b;
b = 4;
const c = 5;
}