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

前端 未结 16 1011
庸人自扰
庸人自扰 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:30

    I've been watching Douglas Crockford's video on this and his explanation for not using increment and decrement is that

    1. It has been used in the past in other languages to break the bounds of arrays and cause all manners of badness and
    2. That it is more confusing and inexperienced JS developers don't know exactly what it does.

    Firstly arrays in JavaScript are dynamically sized and so, forgive me if I'm wrong, it is not possible to break the bounds of an array and access data that shouldn't be accessed using this method in JavaScript.

    Secondly, should we avoid things that are complicated, surely the problem is not that we have this facility but the problem is that there are developers out there that claim to do JavaScript but don't know how these operators work?? It is simple enough. value++, give me the current value and after the expression add one to it, ++value, increment the value before giving me it.

    Expressions like a ++ + ++ b, are simple to work out if you just remember the above.

    var a = 1, b = 1, c;
    c = a ++ + ++ b;
    // c = 1 + 2 = 3; 
    // a = 2 (equals two after the expression is finished);
    // b = 2;
    

    I suppose you've just got to remember who has to read through the code, if you have a team that knows JS inside out then you don't need to worry. If not then comment it, write it differently, etc. Do what you got to do. I don't think increment and decrement is inherently bad or bug generating, or vulnerability creating, maybe just less readable depending on your audience.

    Btw, I think Douglas Crockford is a legend anyway, but I think he's caused a lot of scare over an operator that didn't deserve it.

    I live to be proven wrong though...

提交回复
热议问题