Hoisting behaviour of 'const' and 'let'
Yuh-Ruey Chen
maian330 at gmail.com
Sun Oct 12 13:00:17 PDT 2008
David-Sarah Hopwood wrote:
> Mark S. Miller wrote:
> > On Sat, Oct 11, 2008 at 8:35 PM, David-Sarah Hopwood
> > <david.hopwood at industrial-designers.co.uk> wrote:
> >> The reason for making 'const' hoist to the top of the enclosing block,
> >> AFAIR, was consistency with function declarations. However, there are
> >> good reasons why 'const'/'let' and function declarations should be
> >> treated differently:
> >
> > The following issue invalidates one of your reasons.
> >
> > {
> > .... f(); ...
> >
> > const x = 3;
> >
> > function f() { ... x ... }
> > }
>
> <snip>
>
> > Since functions hoist, if const do not, then in the example above, either
> > 1) we must not allow f to refer to x, or
> > 2) we must still have a read barrier, since f may still be invoked and
> > access x before x is initialized.
>
> 3) we allow f to refer to x, but disallow the reference to f outside the
> scope of x.
>
> More generally,
>
> - if a function refers to a 'let' or 'const' variable, its effective
> scope is intersected with the scope of that variable.
>
> This rule is simple, easy to explain and motivate, does not
> unnecessarily reject "good" programs, and is straightforward to work
> around in cases where the program would be dynamically safe.
> If it is used then no read or write barriers are required.
>
To clarify, would this proposed rule also invalidate the following example?
{
var g = f; // is this what you mean by "reference to f"?
g();
const x = 3;
function f() { ... x ... }
}
Then what about this example?
// global scope
if (cond) // suppose it's true
y = 'f';
this[y]();
const x = 3;
function f() { ... x ... }
This is a case where static analysis would not find the premature call
to f().
More information about the Es-discuss
mailing list