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

Wrong ES3/ES5 code when iterated identifier is reassigned in a 'for...of' statement #5475

Closed
olydis opened this issue Oct 30, 2015 · 2 comments
Assignees
Labels
Bug A bug in TypeScript Fixed A PR has been merged for this issue

Comments

@olydis
Copy link

olydis commented Oct 30, 2015

There is an inconsistency regarding the emitted ES3/ES5 code:

var x = [3, 3, 3];
for (var i of x)
{
    x = [2, 2];
    console.log(i);
}

compiles to

var x = [3, 3, 3];
for (var _i = 0; _i < x.length; _i++) {
    var i = x[_i];
    x = [2, 2];
    console.log(i);
}

printing

3
2

instead of (ES6 semantics)

3
3
3

(Note that the code emitted also differs from the feature description: #2207 (comment))


On the other hand, merely adding parentheses around the expression:

var x = [3, 3, 3];
for (var i of (x))
{
    x = [2, 2];
    console.log(i);
}

correctly compiles to

var x = [3, 3, 3];
for (var _a = 0, _b = (x); _a < _b.length; _a++) {
    var i = _b[_a];
    x = [2, 2];
    console.log(i);
}

giving the expected output.


In other words, it looks like there is some sort of faulty optimization applied: As soon as the expression to iterate over is a bare variable, it is not rescued to a new local (here: _b). As shown, this results in wrong semantics.

@DanielRosenwasser DanielRosenwasser changed the title Wrong ES3/ES5 code emitted for certain 'for...of' statements Wrong ES3/ES5 code when iterated identifier is reassigned in a 'for...of' statement Oct 30, 2015
@DanielRosenwasser DanielRosenwasser added the Bug A bug in TypeScript label Oct 30, 2015
@DanielRosenwasser DanielRosenwasser added this to the TypeScript 1.8 milestone Oct 30, 2015
@DanielRosenwasser DanielRosenwasser self-assigned this Oct 30, 2015
@DanielRosenwasser
Copy link
Member

Thanks for the bug report! You can try out our nightlies by installing npm install -g typescript@next by ~11:30 Pacific tonight or tomorrow morning and you should get the fix.

@DanielRosenwasser DanielRosenwasser added the Fixed A PR has been merged for this issue label Oct 31, 2015
@olydis
Copy link
Author

olydis commented Oct 31, 2015

Amazing, thank you!

@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
Bug A bug in TypeScript Fixed A PR has been merged for this issue
Projects
None yet
Development

No branches or pull requests

2 participants