Uglifyjs: Way to reduce +=1 to ++ in for loops?

Created on 18 Oct 2018  路  7Comments  路  Source: mishoo/UglifyJS

Bug report or feature request?

feature req

Uglify version (uglifyjs -V)

3.4.9

JavaScript input

for(var i = 0; i < 3; i += 1){
  console.log(i);
}

The uglifyjs CLI command executed or minify() options used.

uglifyjs [filename.js]

JavaScript output or error produced.

for(var i=0;i<3;i+=1){console.log(i)}

maybe this is a source code issue and outside the scope of minification, just wondering if there was/could be an option to turn +=1 and -=1 to ++ and -- ?

Most helpful comment

It's very tricky to do correctly, because when the variable is a string it change the meaning:

// 0, 1, 2
for(var i = 0; i < 3; i += 1){console.log(i)}

// "0", "01"
for(var i = "0"; i < 3; i += 1){console.log(i)} //

All 7 comments

Added the feature to terser, under the existing "loops" option.

Released as terser 3.10.8

You might want to pin that version, as I had to revert the feature due to issues. I might try to do it again sometime, but for now it's out.

It's very tricky to do correctly, because when the variable is a string it change the meaning:

// 0, 1, 2
for(var i = 0; i < 3; i += 1){console.log(i)}

// "0", "01"
for(var i = "0"; i < 3; i += 1){console.log(i)} //

Maybe an "assume no implicit type coercion anywhere" optimization flag could be useful?

@drathier, you'd have to specify it much more clearly than that. E.g. I agree that "hello" + 123 is implicit, but "" + 123 is an explicit conversion - that's the easiest way to convert a number to a string.

"hello" + 123 is just as explicit as "" + 123. What I meant was that n + 123 could assume that n is a number

Was this page helpful?
0 / 5 - 0 ratings

Related issues

JoeUX picture JoeUX  路  3Comments

PinkyJie picture PinkyJie  路  3Comments

Havunen picture Havunen  路  5Comments

buu700 picture buu700  路  5Comments

GrosSacASac picture GrosSacASac  路  3Comments