Hoisting behaviour of 'const' and 'let'

David-Sarah Hopwood david.hopwood at industrial-designers.co.uk
Tue Oct 14 05:53:33 PDT 2008


David-Sarah Hopwood wrote:
> Igor Bukanov wrote:
>> 2008/10/13 David-Sarah Hopwood <david.hopwood at industrial-designers.co.uk>:
>>> This is slightly more complex than I'd hoped, but I think the guarantee
>>> that it is never possible to see uninitialized values of 'const' or 'let'
>>> variables is worth it.
>> What about the functions introduced in the let or const initializers?
>> Like the following 2 examples, where the first does access the
>> unitilized value but the second does not.
>>
>> const x = (function() { return x; })()
> 
> Invalid because x is not in scope in its own initializer.
> 
>> versus
>>
>> var f = null;
>> const x = (f = function() { return f ? x : null;})()
> 
> Same here. The same effect, apart from x not being const, can be
> achieved by:
> 
>   var f = null;
>   let x; x = (f = function() { return f ? x : null;})();
> 
> In this case the compiler's analysis is not powerful enough to guarantee
> that x is observationally immutable (unsurprisingly, at least because the
> condition of the ?: could have been an arbitrary expression),

Oh, and because there's a bug in your example: it does access x before
it is assigned (first f is assigned, then the function is called, then
x is assigned). So my proposed scoping rule found a bug that both you
and I initially missed.

-- 
David-Sarah Hopwood


More information about the Es-discuss mailing list