Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

let variable shadowing let variable of same name cannot reference outer variable in initialiser #7939

Closed
myitcv opened this issue Apr 7, 2016 · 2 comments
Labels
By Design Deprecated - use "Working as Intended" or "Design Limitation" instead

Comments

@myitcv
Copy link

myitcv commented Apr 7, 2016

Tested with 1.8 and 1.9.0-dev.20160406

Is it intentional that the following fails to compile?

let x = 5;

{
    console.log(x); // Block-scoped variable 'x' used before its declaration
    let x = x;      // Block-scoped variable 'x' used before its declaration
    console.log(x);
}

The inner x is effectively shadowing the outer x, but only at and after the point it is redefined (i.e. the inner let x)

I couldn't find any specific mention of this in #904 which appears to be the documentation for let right now (via the spec)

Thanks

@DanielRosenwasser DanielRosenwasser added the By Design Deprecated - use "Working as Intended" or "Design Limitation" instead label Apr 7, 2016
@DanielRosenwasser
Copy link
Member

It's actually part of the ECMAScript standard. Every block introduces its own environment record and creates a local binding for each lexical declaration (i.e. each let, const, etc.). That means that even if you shadow an outer variable later in your block, any prior uses in the block will still refer to the one declared later in the same block.

In an ES2015+ runtime, that would cause a ReferenceError to get thrown. In TypeScript, we give you a compile-time error.

@myitcv
Copy link
Author

myitcv commented Apr 7, 2016

@DanielRosenwasser thanks very much, I should have thought to check the ECMAScript standard too. Totally clear from the spec.

@microsoft microsoft locked and limited conversation to collaborators Jun 19, 2018
Sign up for free to subscribe to this conversation on GitHub. Already have an account? Sign in.
Labels
By Design Deprecated - use "Working as Intended" or "Design Limitation" instead
Projects
None yet
Development

No branches or pull requests

2 participants