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;

Answers:

Answer

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;.

Answer

Use prefix operator. It's because with postfix, value is incremented after its first read. With prefix you will get updated count value before it read.

count = checkArr(arr) ? ++count : count;

Should work

Answer

It is legal to use ternary operator like this. However I would argue about code style here.

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

In this line expressionFalse part (after :) is completely useless and doesn't do anything and it's there only to make ternary operator syntax correct.

For this case IMO following construction is more readable:

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

or

if (checkArr(arr)) ++count;
Answer

the value of count++ and ++count is different.

In short:

count = count++ : The value of count++ is the value BEFORE the increment.

count = ++count : The value of ++count is the value AFTER the increment.

let count = 5;
console.log(count++); //return 5
console.log(count); //return 6

let count = 10;
console.log(++count); //return 11
console.log(count); //return 11

This works the same for count-- and --count

However, one thing to note here is in eslint this would be considered error, and it's recommended to use +=1 instead.

Link fyi: https://eslint.org/docs/rules/no-plusplus

Tags

Recent Questions

Top Questions

Home Tags Terms of Service Privacy Policy DMCA Contact Us

©2020 All rights reserved.