Hoisting behaviour of 'const' and 'let'

Brendan Eich brendan at mozilla.com
Mon Oct 13 15:16:46 PDT 2008


On Oct 12, 2008, at 1:45 PM, David-Sarah Hopwood wrote:

> Peter Michaux wrote:
>> On Sun, Oct 12, 2008 at 12:11 PM, David-Sarah Hopwood
>> <david.hopwood at industrial-designers.co.uk> wrote:
>>> Peter Michaux wrote:
>>>> David-Sarah wrote:
>>>>>
>>>>> (function () {
>>>>> print(x);
>>>>> { const x = 42; }
>>>>> })();
>>>>>
>>>>> (calls 'print(undefined)').
>>
. . .
>> It would be completely unintelligible to read code where the print
>> above shows "42".
>
> Of course. In both my proposal and in the current draft of ES3.1, this
> is a static error, because x isn't in scope at the 'print' -- except
> that if there is an x declared in some surrounding scope, that x is  
> used.

No, not in ES3.1 -- quoting from the latest (draft13oct08), section  
12.15:

If the constant statement occurs directly inside a  
FunctionDeclaration, the constants are defined with
function-local scope in that function, as described in s10.1.3. If a  
constant statement occurs inside a Block,
the constants are defined with block-local scope. Otherwise, they are  
defined with global scope (that is,
they are created as members of the global object, as described in  
10.1.3) using property attributes {
[[Writable]]: false, [[Enumerable]]: true, [[Configurable]]: false }.  
Constants are created when the
execution scope is entered. Constants have no value when created. A  
constant is assigned the value of the
AssignmentExpression of it‘s Initialiser when the ConstantStatement is  
executed, not when the constant is
created. Any attempts to access the value of a constant before it is  
assigned a value throws a
ReferenceError exception.


> (Static errors might still be reported at run-time, depending on what
> kind of environment the code is running in.)

Then they are not static errors and the spec should not call them  
that. Static == compile time. The spec should not require static  
analysis without a lot more discussion of the trade-offs for small  
implementations.

/be


More information about the Es-discuss mailing list