Hoisting behaviour of 'const' and 'let'

David-Sarah Hopwood david.hopwood at industrial-designers.co.uk
Sun Oct 12 14:20:07 PDT 2008


David-Sarah Hopwood wrote:
> Yuh-Ruey Chen wrote:
>> David-Sarah Hopwood wrote:
>>> Mark S. Miller wrote:
>>>> {
>>>>     .... f(); ...
>>>>
>>>>     const x = 3;
>>>>
>>>>     function f() { ... x ... }
>>>> }
>>> <snip>
>>> 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 ... }
>> }
> 
> Yes. Since 'x' is a free identifier of 'f' and there exists a (single)
> 'const' or 'var' declaration of 'x' in the same block, 'f' is not in
> scope until after that declaration of x.
> 
> (To fill in some details: multiple initializers are treated as if they
> were separate statements, e.g. "var a = x, b = y;" is equivalent to
> "var a = x; var b = y;". A variable is not in scope in its own initializer.
> If there are multiple declarations of a 'const' or 'let' variable x in
> a block, then no function in that block can refer to x, since it is not
> clear which x is meant.

Actually that restriction about multiple declarations isn't necessary:
the variable reference is resolved as normal depending on where the
function is written, and the scope of the function identifier is
intersected with the scope of that particular variable instance.

-- 
David-Sarah Hopwood


More information about the Es-discuss mailing list