Friday, May 17, 2024
 Popular · Latest · Hot · Upcoming
43
rated 0 times [  50] [ 7]  / answers: 1 / hits: 15326  / 13 Years ago, thu, june 16, 2011, 12:00:00

on my quest to learn and improve my JavaScript I came across a script that has a switch / case statement and I noticed some variables are incremented using ++ with the variable before the ++ and then some variables have the ++ after the variable. What's the difference between these? Here's an example of what I'm trying to explain notice the m and y variables.



 switch(f){
case 0:{

++m;
if(m==12){
m=0;
y++;
}
break;
}
case 1:{

--m;
if(m==-1){
m=11;
y--;
}
break;
}
case 2:{

++y;
break;
}
case 3:{

--y;
break;
}
case 4:{

break;
}
}

More From » javascript

 Answers
12

++i returns the value of i after it has been incremented. i++ returns the value of i before incrementing.



When the ++ comes before its operand it is called the pre-increment operator, and when it comes after it is called the post-increment operator.



This distinction is only important if you do something with the result.



var i = 0, j = 0;

alert(++i); // alerts 1
alert(j++); // alerts 0


One thing to note though is that even though i++ returns the value before incrementing, it still returns the value after it has been converted to a number.



So



var s = 1;
alert(typeof s++); // alerts number
alert(s); // alerts 2, not 11 as if by (1 + 1)

[#91664] Wednesday, June 15, 2011, 13 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
jackie

Total Points: 442
Total Questions: 107
Total Answers: 94

Location: Honduras
Member since Sun, Dec 26, 2021
2 Years ago
jackie questions
Sat, Sep 18, 21, 00:00, 3 Years ago
Wed, Jul 14, 21, 00:00, 3 Years ago
;