If I have
a = 0;
if(a++ < 1){
console.log(a);
}
I get the value 1 in the console. If a became 1 with the incrementation, then why did the expression evaluate true?
If I do
a = 0;
if(++a < 1){
console.log(a);
}
Then I don’t get anything in the console, meaning the expression evaluated to be false.
I have always used variable++ to increment variables in for loops and the like. I have seen the ++variable, but I assumed it was another way to write the same thing. Can someone explain what happens and why? What’s the difference between the two?
Does ++variable increment the variable at the time of evaluation, while variable++ increments after?
No, they’re not the same at all.
++variableis pre-increment.It increments
variableand evaluates to the new value.variable++is post-increment.It increments
variableand evaluates to the old value.This is common to most C-style languages, including C itself, C++, PHP, Java and Javascript.
i.e.:
Yes, exactly. 🙂