Why avoid increment (“++”) and decrement (“--”) operators in JavaScript?

前端 未结 16 1344
庸人自扰
庸人自扰 2020-11-22 06:23

One of the tips for jslint tool is:

++ and --
The ++ (increment) and -- (decrement) operators have been known to contribute

16条回答
  •  闹比i
    闹比i (楼主)
    2020-11-22 06:35

    In a loop it's harmless, but in an assignment statement it can lead to unexpected results:

    var x = 5;
    var y = x++; // y is now 5 and x is 6
    var z = ++x; // z is now 7 and x is 7
    

    Whitespace between the variable and the operator can lead to unexpected results as well:

    a = b = c = 1; a ++ ; b -- ; c; console.log('a:', a, 'b:', b, 'c:', c)
    

    In a closure, unexpected results can be an issue as well:

    var foobar = function(i){var count = count || i; return function(){return count++;}}
    
    baz = foobar(1);
    baz(); //1
    baz(); //2
    
    
    var alphabeta = function(i){var count = count || i; return function(){return ++count;}}
    
    omega = alphabeta(1);
    omega(); //2
    omega(); //3
    

    And it triggers automatic semicolon insertion after a newline:

    var foo = 1, bar = 2, baz = 3, alpha = 4, beta = 5, delta = alpha
    ++beta; //delta is 4, alpha is 4, beta is 6
    

    preincrement/postincrement confusion can produce off-by-one errors that are extremely difficult to diagnose. Fortunately, they are also complete unnecessary. There are better ways to add 1 to a variable.

    References

    • JSLint Help: Increment and Decrement Operators

提交回复
热议问题