A couple of questions regarding let, hoisting and block scope

David Herman dherman at mozilla.com
Mon Mar 21 12:22:49 PDT 2011


>   Hoisting isn't nice in general, and from the "no use before    declaration" in [1], it seems that let bindings won't be hoisted,
>   not even to their enclosing block.

That page is not yet complete. There's plenty more work to do on it, but we probably won't be able to find much time to do that work till after May, I'm afraid.

>   But hoisting is also the basis for making mutually recursive
>   function definitions work without pain. Will we have to    declare all function names of recursive function groups    ahead of defining them (with a top-down parser, there'd
>   be many more than just two function names to list)?

Function declarations (whether via |function foo(...) { ... }| or |const #foo(...) { ... }|) will almost certainly be hoisted.

>   {    let odd, even; // needed?
>   odd = function (n) { .. even(n-1) ..}
>   even = function (n) { .. odd(n-1) ..}
>   }

Pre-declaring odd and even would be needed for this form, yes. (If someone wants to change JS to have Python/CoffeeScript-like implicit variable scope, they'll have to get past my dead body first.) But for function definitions, you're better off using function declarations rather than assignment.

>   or, with #functions [2]
> 
>   {    const odd, even; // needed?
>   const #odd (n) { .. even(n-1) ..}
>   const #even (n) { .. odd(n-1) ..}
>   }

As I say, since these are the declarative form, you get hoisting and don't need to pre-declare them.

Working out the details of the scoping semantics is really subtle, though. When you have hoisting of functions, the spec has to cope with situations like:

    {
        let x;
        {
            foo();
            let x;
            function foo() { ... x ... }
        }
    }

There are a bunch of careful details we have to work through, but we haven't gotten to it yet.

This really isn't a good time or venue to discuss the details. The spec isn't complete or ready for review, and es-discuss is not the place to do that work.

>   One idea would be to start separating "strong" and "weak"
>   blocks, where weak blocks '{ }' are the standard, non-scoped
>   ones and strong blocks '{{ }}' (to steal no syntax) would be
>   block-scoped (for instance, map to "(function() { }())" ).

Ugh. Just... no.

Dave



More information about the es-discuss mailing list