Hoisting behaviour of 'const' and 'let'

David-Sarah Hopwood david.hopwood at industrial-designers.co.uk
Sun Oct 12 13:45:31 PDT 2008


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)').
>>>
>>> The expected output should be "undefined", shouldn't it?
>>
>> For some definition of "expected". That's what it does in FF3 (I don't
>> have Safari or Opera installed, and IE7 throws a SyntaxError), but I
>> don't think it is expected, or useful, that a const variable can
>> effectively be mutable. For 'var' there are potential uses of hoisting
>> (even if they would be more clearly expressed in other ways), but not
>> really for 'const'.
> 
> Either const should not hoist, the print above should show
> "undefined", or an error is thrown "using a const not yet assigned."
> 
> 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.

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

-- 
David-Sarah Hopwood


More information about the Es-discuss mailing list