Beginning AngularJS

(WallPaper) #1

ChApter 1 ■ JAvASCrIpt You Need to KNow


In all cases, the value of myNumber increments by 1. Take special note here that the preceding increment operator
appears before the variable myNumber. In this case, we refer to it as a pre-increment. A post-increment, as you might
expect, would look like this:


myNumber = myNumber++;


This seems straightforward enough, so why am I treating these operators as a special case? Because, potentially,
there is a serious mistake that can be made when using them. This is demonstrated in Listing 1-16.


Listing 1-16. Pre- vs. Post-Increment Behavior


<!DOCTYPE html>




JavaScript Primer





Read through Listing 1-15, and see if you can figure out why the output is as shown following. The answer lies in
the nature of how or, rather, when these operators perform their work.


Pre-increment result is 3
Post-increment result is 2


If you found it odd that the post-increment result was 2 instead of 3, here’s why: the post increment operation
happens after the assignment operation. Let me clarify this by breaking it down a bit.


myNumber = ++myNumber;


Reading the preceding code snippet in plain English, you might say this: “Increment the current value of
myNumber, and then store it into the variable myNumber.” However, if you look at the post-increment variation of this:


myNumber = myNumber++;

Free download pdf