- Notifications
You must be signed in to change notification settings - Fork4
CS2 Discussion: Features: Block assignment let and const operators #35
Description
Building off of#1 andthis comment, the great advantage oflet
/const
is its block-scoping, i.e.:
leta=1;if(true){letb=2;}console.log(b);// undefined
This is a dramatic improvement overvar
, and a big reason whylet
andconst
have become popular features. This block scoping is probably something that CoffeeScript should have, separate from the feature ofconst
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 asvar
, in that its declaration is hoisted to its entire scope (whatMDN refers to as thetemporal dead zone), solet
declarations should be grouped together at the top of their block scope similar to howvar
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=1b :=2c :==3if (yes) b :=4 c :==5
would compile into this #"auto" data-snippet-clipboard-copy-content="var a;let b;a = 1;b = 2;const c = 3;if (true) { let b; b = 4; const c = 5;}">
vara;letb;a=1;b=2;constc=3;if(true){letb;b=4;constc=5;}