Skip to content

const / let scopes are different from native JS engines (V8 and SpiderMonkey) #26764

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

Closed
gfx opened this issue Aug 30, 2018 · 2 comments
Closed
Labels
Duplicate An existing issue was already created

Comments

@gfx
Copy link

gfx commented Aug 30, 2018

TypeScript Version: 3.0.1

Search Terms: variable scope es2015 label:Bug

Code

function f() {
  console.log("foo:", foo);
}

f(); // => foo: undefined
let foo = 42;
f(); // => foo: 42

Expected behavior:

In V8 (nodejs, chrome) and SpiderMonkey (firefox), it can't compile it runs with ReferenceError if foo is not initialized.

Actual behavior:

It compiles and runs, showing foo: undefined and foo: 42.

Playground Link: playground

Related Issues: #19503 looks similar, I guess.

@gfx gfx changed the title const / let const / let scopes are different from native JS engines (V8 and SpiderMonkey) Aug 30, 2018
@ghost
Copy link

ghost commented Aug 30, 2018

Seems like a duplicate of #11498.
Currently TypeScript never considers when a function is called when checking it. So it assumes any variables it closes over will have been defined by the time the function is called.

If this was instead a suggestion to copy the runtime behavior and throw ReferenceError instead of getting undefined when transpiling to es5, that's probably too expensive to do for every variable that happens to be used in a closure -- and we currently have no way of detecting that a function is called only when its closed-over variables have already been defined, so we would have to do that for every variable.

Note that if you don't need to support old browsers you can set --target es6 which would solve the issue for you.

@ghost ghost added the Duplicate An existing issue was already created label Aug 30, 2018
@typescript-bot
Copy link
Collaborator

This issue has been marked as a 'Duplicate' and has seen no recent activity. It has been automatically closed for house-keeping purposes.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
Duplicate An existing issue was already created
Projects
None yet
Development

No branches or pull requests

2 participants