ASP.NET Bundler JavaScript for of and for in variable name collision bug when using let or const

Benjamin Dransfield 20 Reputation points
2024-01-19T04:33:26.5833333+00:00

I've ran into what I believe is a bug in the Bundler which is part of ASP.NET. If you declare a JavaScript function which takes in a value, iterates over it using either a for in or a for of loop, and use either const or let (var behaves properly) to declare the resulting value of the iteration the bundler will minify both variable names to the same value, resulting in a ReferenceError when the function is called. For instance if the unbundled version is this:

function forInConst(arr) {
    for (const arr_item in arr) {
        console.log(arr_item);
    }
}

The bundler will emit the following:

function forInConst(n){for(const n in n){console.log(n);}}

Upon calling the function Chromium based browsers will log "ReferenceError: Cannot access 'n' before initialization" and Firefox will log "ReferenceError: can't access lexical declaration 'n' before initialization".
Aside from using var, one workaround is to add a reference to the iterated value within the loop. So this version will not show the bug, but does spam the console:

function forInConst(arr) {
    for (const arr_item in arr) {
        console.log(arr_item);
        console.log(arr);
    }
}

I've created a simple demonstration app that show all permutations of for of/for in, const/var/let, and bundled/unbundled/worked-around all on a single page when the project is ran. Source can be found here: https://github.com/bdrans/BundlerMinificationBug

ASP.NET
ASP.NET
A set of technologies in the .NET Framework for building web applications and XML web services.
3,168 questions
{count} votes

Accepted answer
  1. Bruce (SqlWork.com) 52,486 Reputation points
    2024-01-23T21:48:11.2833333+00:00

    not surprising. your project is using webgrease which has been retired for almost a decade and does not receive updates. you should pick a more modern bundler.

    note: Microsoft does not supply one, you will need to pick an open source bundler. Mads has a newer tool:

    https://github.com/madskristensen/BundlerMinifier/blob/master/README.md

    note: I typically use Webpack.

    https://webpack.js.org


0 additional answers

Sort by: Most helpful