Increment(++) — javaScript

Andrew Park
2 min readMay 23, 2021

I was writing a code to increment “likes” count when a button is clicked and a condition is met. Simple enough…I thought. However, for some reason the count would not increment on the first click.

Below is simplified code that I had:

I threw in console.log(voteCount) in line 14, and I found a weird behavior. On the first click, the return value of increaseLike() function was 0. On the second click, the return value was 1.

It turned out that if I use increment (++) after operand, it returns the value before incrementing.

MDN Web Docs states (https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Increment):

“If used postfix, with operator after operand (for example, x++), the increment operator increments and returns the value before incrementing.”

“If used prefix, with operator before operand (for example, ++x), the increment operator increments and returns the value after incrementing.”

So, in my code, on the first click, the return value of increaseLike() function was 0 (return 0 (current value) first, and then increase the vote.likes to 1).

Once I changed the line 9 with increment(++) before the operand (vote.likes), increment worked as expected.

Who know, placing operator in a wrong place can cause an unexpected behavior.

--

--