mardi 11 août 2015

Incrementing variables inside conditional statements

So, I recently thought I was being really clever (something I've learned is not always a good trait when programing) and tried to refactor something like this:

counter++
if (counter > something) {
    doThisCoolThing()
}

into something like this

if (++counter > something) {
    doThisCoolThing()
}

but I was immediately told that I shouldn't do this and had to move the counter incrementing back up a line.

I scoured the internet for information on the subject, and I came up with a few pages on the MDN, the most relevant saying "The increment operator increments (adds one to) its operand and returns a value. [...] If used prefix with operator before operand (for example, ++x), then it returns the value after incrementing.", which seems to indicate that incrementing a variable inside a conditional statement would be completely legitimate. The only somewhat related warning I could find was regarding simple assignment, e.g. if (x = y), but that if ((x = y)) was okay.

I just wanted to get some other opinions on this. Is it bad practice or is it completely valid?

Thank you

Aucun commentaire:

Enregistrer un commentaire