DEV Community


Discussion on: What does "if(variable++)" do in Javascript

mellen profile image
Matt Ellen • Edited

You can say, code-wise, it is equivalent to

  // do stuff
Enter fullscreen mode Exit fullscreen mode

++ is a unary increment operator. As a postfix operator it returns the value of the object being referenced and then increments the value of the object. This means that the if statement sees the value before it is incremented.

In javascript if statements can evaluate any expression that results in a value (which I think is literally any expression), because all values are either truthy or falsey, i.e. if can treat them as boolean.

(Try evaluating if(console.log('hello')){console.log('you');}else{console.log('world');}. This works because console.log actually returns undefined, which is falsey.)

Since val++ results in a value, it can be evaluated in an if statement.

That's not a very "like I'm 5" explanation.

Imagine you have a lever you can pull. When you pull the lever there is a device that checks the contents of a box and then puts one more item in the box. (Luckily the box is similar to Mary Poppin's carpet bag.) Boxes that are not empty when checked get shot to the moon. If the box is empty when the check occurred then the only thing that happens is that there is now an item in the box.

So if you want to send an empty box to the moon you have to pull the lever twice. This also means that moon boxes have a minimum of two items in them.

The same is true for --, but there are some differences. The lever in this situation would be removing items from a box, so if there is only one item in the box, then it would go to the moon empty. Also, if the box were empty and you pull the lever twice to send it, it would have two lots of antimatter in it.

Personally I recommend against this style of programming, because you have to think about how it works way more than incrementing outside of the conditional.