++ operator

windows

Guest
Yo people<br /><br />Going through my javascript book today and all is going swimmingly well. Im not sure what is going on so I might be stupid but seems to be exactly how its supposed to be in the book.<br /><br />If i stick a ++ or -- before a variable the code works as it should. However if I put them after the variables as in the code below it completely ignores it and still returns Answer=7 rather than Answer=8. Have i overlooked something?<br /><br /><div class='codetop'>CODE</div><div class='codemain' style='height:200px;white-space:pre;overflow:auto'><script language="javascript" type="text/javascript"><br /><br />var firstNumber;<br />var secondNumber;<br />var Answer;<br /><br />firstNumber=2;<br />secondNumber=5;<br /><br />Answer= firstNumber++ + secondNumber;<br /><br />alert(Answer);<br /><br /></script></div><br /><br /><!--content-->
Yep, that's the difference between a prefix operator (++firstNumber) and a postfix operator (firstNumber++)<br /><br />When you're using firstNumber++, you're not being ignored, but the addition takes place <i>after</i> the line that it appears on.<br /><br />e.g:<br /><br /><!--c1--><div class='codetop'>CODE</div><div class='codemain'><!--ec1-->number = 1;<br />alert(++number); // This increments on the same line, so will display "2"<br />alert(number);   // This will also show "2"<br /><br />number = 1;<br />alert(number++); // This increments after this line, so will display "1"<br />alert(number);   // The postfix increment from above is now in effect, so this will display "2"<!--c2--></div><!--ec2--><!--content-->
Thanks mate I just used your example and thats shined light on it. Thanks a lot for that!<!--content-->
 
Top