Search code examples
javascriptternary

Is it ok to use count + 1 in ternary operator?


What I want to do is check if there is element in array, if it is, I want to increment counter. Compiler reports error when I do count++ but not when I do count + 1, and it increments correctly. Is it because count++ is operation and not an expression, and count + 1 is expression?

let count = 0;

//not working
count = checkArr(arr) ? count++ : count;

//working
count = checkArr(arr) ? count + 1 : count;


Solution

  • Nothing is forbidden, but some good practice can be adopted.

    Mixing up assignation count =, conditioning ?: and post incrementation ++ is a lot inside of a same line.

    Always go for the simpliest solution when coding something. In your case :

    if (checkArr(arr)) {
      count += 1;
    }
    

    is way easier to understand than a ternary which does not seems to be appropriate in that particular context.


    There are existing tool auditing code quality, as sonarqube, eslint ...

    They are always requiring simplicity.

    Example about ternary rules :

    Example about post/pre incrementation :

    They want coder to avoid the use of ++/-- because for some people it can be misleading. A lot of people do not know the difference between ++var and var++ which may led to bugs. Prefer var += 1;.