Search code examples
javascriptuglifyjs

UglifyJS changes the code bahaviour


I have the following code (simplified for the sake of discussion):

var a = 1;
var b = [];
if (checkIfAisOne(a)) {
    b = ['something']
}
console.log(b);
//['something']

then there is a Grunt Uglify task which converts this code to this:

checkIfAisOne(a) || (b = ['something']), console.log(b);
// []

Because the first part of the expression is true, the second part (after ||) is not executed and therefore b remains unchanged.

So, uglified code shows different output than non-uglified code.

Is that a known issue? A bug? How it can be prevented, is there any option/setting to fix this?


Solution

  • Latest uglifyJS is producing this output:

    var a=1,b=[];checkIfAisOne(a)&&(b=["something"]),console.log(b);
    

    Using https://github.com/mishoo/UglifyJS2/commit/a0e03c9df47c411a40bceef02af2ce3dd1a329cc, which is committed on 3/5/2016 but merged in repo 4/5/2016. The output is the same for UglifyJS v2.6.2.

    UglifyJS v2.6.2 is shipped with grunt-contrib-uglify 1.0.0 and later. So please upgrade grunt-contrib-uglify if necessary.

    If there is still a problem with the output, feel free to open an issue on https://github.com/mishoo/UglifyJS2 with the code snippet