Incrementing and Decrementing Variables with ++ and —

Mav Tipi
The Startup
Published in
2 min readDec 24, 2020

--

(Medium styles two minus signs as an em dash, like this: — . But we’re talking about two minus signs.)

Incrementing a variable is one of the most common things you do as a programmer. The simplest way is to take itself and add 1:

variable = variable + 1 // Increment
variable = variable - 1 // Decrement

The variable takes itself and adds one, and assigns that new value to itself. Pretty simple. You can write those lines in basically any language.

Most modern languages will also allow this more concise version:

variable += 1
variable -= 1

I don’t think R does, for example, but most do. Also, check your language’s documentation on this (it’ll be called augmented assignment or compound assignment); there may be niche ways that it differs functionally from the first way, especially when using it on something other than a number.

Now, some languages let you go one further. C-family languages, JavaScript, and probably some scattered others have this syntax:

variable ++
variable --

We’ve lost the ability to specify a number to increment by; it’s always 1. But it’s very handy; some keystrokes saved in one of the most common lines you’ll write. There’s also this:

++ variable
-- variable

Which works slightly differently. With ++variable, the variable will be incremented and then evaluated; with variable++, it’ll be evaluated and then incremented. Here’s a case where they’re different (written in JS):

let number = 3
if (number++ > 3)
console.log("It's greater than 3.")
else
console.log("It isn't greater than 3")
console.log(`The number is ${number}`)
#=>It isn't greater than 3.
The number is 4.
let number = 3
if (++number > 3)
console.log("It's greater than 3.")
else
console.log("It isn't greater than 3")
console.log(`The number is ${number}`)
#=>It's greater than 3.
The number is 4.

In both cases, the number incremented. (Yes, even though it’s in a conditional check. It would work that way for the previously-discussed methods of incrementing, too.) But in the first case, it evaluated and then incremented, and in the second case, it incremented and then evaluated.

I hope this is useful. But once again, as with any tip on a new feature or syntax, you have to check your docs. There are always quirks.

--

--