Skip to content

Duplicated names in var statements are considered as different variables #685

Closed

Description

@RubenVerborgh

1. Minimal code to reproduce the bug

Input Code

function f() {
  var a = 1;
  var b = a;
  var a = 2;
  console.log(a, b);
}
f();

or

function f() {
  var a = 1, b = a, a = 2;
  console.log(a, b);
}
f();

Live example on babeljs.io

Actual Output

function f(){var c=1,c=2;console.log(c,c)}f();

Expected Output

function f(){var c=1,d=c;c=2,console.log(c,d)}f();

Details

Note the incorrect constant propagation in the console.log statement: it has console.log(c,c), even though the two arguments in the original are different. This happens because the variable a is declared multiple times as var, yet is not recognized as the same variable.

In the correct interpretation a=2 is recognized as a modification to the same variable, so constant propagation is not allowed to happen. Changing the second var a to simply a makes the problem disappear.

Slightly more complex example:

function loop() {
  var end = 0;
  var start = end;
  while (end < 10) {
    console.log(start, end);
    var end = end + 1;
  }
}

2. Stack Trace if there is an Error thrown during minification

None.

3. Configuration - babel-minify configuration or babelrc

Default.

The problem is with the deadcode option (babel-plugin-minify-dead-code-elimination), which is switched on by default.

4. Whether you used it with other presets/plugins - like es2015 or env

None.

5. Environment: gulp, rollup, webpack, babel-cli, etc...?

All.

Activity

  1. added
    babel
    has PR
    on Sep 9, 2017
  2. added
    bug
    and removed
    has PR
    on Oct 25, 2017
  3. added this to the 1.0 milestone on Nov 18, 2017
  4. added a commit that references this issue on Dec 9, 2017
  5. added a commit that references this issue on Dec 11, 2017
    dc015c6
  6. added
    has PR
    and removed
    babel
    on Dec 11, 2017
  7. added a commit that references this issue on Dec 11, 2017
    7f4dc3d
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    bughas PR

    Type

    No type

    Projects

    No projects

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions