Your Code Makes Baby Jesus Cry

Javascript:

if (!totCnt > 0)

This code properly evaluates as “if totCnt is not greater than zero.” Why?

When the greater comparison is evaluated, both sides of the comparison must be evaluated. Evaluating the left side, we see that the logical not operator is applied to totCnt, an integer. This means that totCnt must be typecast to boolean prior to the application of the operator. When the typecast is carried out, if totCnt is zero, then totCnt is converted to false. The logical not operator is applied, and so totCnt now has the value true. The comparison requires an integer, so the boolean true must be typecast back to an integer, which in this case happens to be MAX_INT. MAX_INT is greater than zero, and so the condition is satisfied.

If totCnt is greater than zero, when it is typecast from an integer to a boolean, its value becomes true, since the integer is non-zero. Negating this, the value of totCnt becomes false. This is typecast back to an integer, which in this case is zero. Zero is not greater than zero, and so the condition is not satisfied.

So the code works, but not for any of the reasons the person who wrote it thought. The code the person wanted to write was:

if (!(totCnt > 0))

or better yet:

if (totCnt == 0)