18.04.2016 Views

Professional JavaScript For Web Developers

javascript for learners.

javascript for learners.

SHOW MORE
SHOW LESS

Create successful ePaper yourself

Turn your PDF publications into a flip-book with our unique Google optimized e-Paper software.

ECMAScript Basics<br />

var iNum = 10;<br />

--iNum;<br />

alert(iNum); //outputs “9”<br />

alert(--iNum); //outputs “8”<br />

alert(iNum); //outputs “8”<br />

The second line decrements num, and the third line displays the result (“9”). The fourth line displays<br />

num once again, but this time the prefix decrement is applied in the same statement, which results in<br />

the number “8” being displayed. To prove that all decrements are complete, the fifth line once again<br />

outputs “8”.<br />

The prefix increment and decrement are equal in terms of order of precedence when evaluating a mathematical<br />

expression and, therefore, are evaluated left to right. <strong>For</strong> instance:<br />

var iNum1 = 2;<br />

var iNum2 = 20;<br />

var iNum3 = --iNum1 + ++iNum2; //equals 22<br />

var iNum4 = iNum1 + iNum2; //equals 22<br />

In the previous code, iNum3 is equal to 22 because the expression evaluates to 1 + 21. The variable<br />

iNum4 is also equal to 22 and also adds 1 + 21.<br />

Postfix increment/decrement<br />

Two operators, also taken directly from C (and Java), are the postfix increment and postfix decrement.<br />

They also add one to a number value, as indicated by the two plus signs (++) placed after a variable:<br />

var iNum = 10;<br />

iNum++<br />

As you might expect, postfix decrement subtracts one from a value and is indicated by two minus signs<br />

(– –) placed after the variable:<br />

var iNum = 10;<br />

iNum--;<br />

The second line of code decreases the value of iNum to 9.<br />

Unlike the prefix operators, postfix operators increment or decrement after the containing expression is<br />

evaluated. Consider the following example:<br />

var iNum = 10;<br />

iNum--;<br />

alert(iNum); //outputs “9”<br />

alert(iNum--); //outputs “9”<br />

alert(iNum); //outputs “8”<br />

Just as in the prefix example, the second line decrements iNum, and the third line displays the result (9).<br />

The fourth line displays num once again, but this time the postfix decrement is applied in the same statement.<br />

However, because the decrement doesn’t happen until after the expression is evaluated, this alert<br />

also displays the number 9. When the fifth line is executed, the alert displays 8, because the postfix<br />

decrement was executed after line 4 but before line 5.<br />

35

Hooray! Your file is uploaded and ready to be published.

Saved successfully!

Ooh no, something went wrong!