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

前端 未结 16 1356
庸人自扰
庸人自扰 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条回答
  •  半阙折子戏
    2020-11-22 06:36

    My 2cents is that they should be avoided in two cases:

    1) When you have a variable that is used in many rows and you increase/decrease it on the first statement that uses it (or last, or, even worse, in the middle):

    // It's Java, but applies to Js too
    vi = list.get ( ++i );
    vi1 = list.get ( i + 1 )
    out.println ( "Processing values: " + vi + ", " + vi1 )
    if ( i < list.size () - 1 ) ...
    

    In examples like this, you can easily miss that the variable is auto-incremented/decremented or even remove the first statement. In other words, use it only in very short blocks or where the variable appears in the block on just a couple of close statements.

    2) In case of multiple ++ and -- about the same variable in the same statement. It's very hard to remember what happens in cases like this:

    result = ( ++x - --x ) * x++;
    

    Exams and professional tests asks about examples like above and indeed I've stumbled upon this question while looking for documentation about one of them, but in real life one shouldn't be forced to think so much about a single line of code.

提交回复
热议问题