↑

Main Page

# Unary plus and minus

The postfix increment and decrement are also equal in terms of order of precedence when evaluating a

mathematical expression, and they are both evaluated left to right. For instance:

var iNum1 = 2;

var iNum2 = 20;

var iNum3 = iNum1-- + iNum2++; //equals 22

var iNum4 = iNum1 + iNum2; //equals 22

In the previous code,

iNum3

is equal to

22

because the expression evaluates to 2 + 20. The variable

iNum4

is also equal to

22

, although it evaluates 1 + 21 because the increment and decrement aren’t com-

pleted until after the value of

iNum3

has been assigned.

Unary plus and minus

The unary plus and minus are familiar symbols to most people and operate the same way in

ECMAScript as they do in high school math. The unary plus essentially has no effect on a number:

var iNum= 25;

iNum = +iNum;

alert(iNum); //outputs “25”

In this code, the unary plus is applied to the number

25

, which returns the exact same value. Although

unary plus has no effect on numbers, it has an interesting effect on strings: It converts them to numbers.

var sNum = “25”;

alert(typeof sNum); //outputs “string”

var iNum = +sNum;

alert(typeof iNum); //outputs “number”

This code converts a string representation of

25

into the actual number. When the unary plus operates

on strings, it evaluates strings the same way as

parseInt()

with one major difference: Unless the string

begins with

“0x”

(indicating a hexadecimal number), the string is converted as if it were decimal. So

“010”

is always 10 when converted using unary plus, however,

“0xB”

is converted to 11.

The unary minus, on the other hand, negates the value of a number (for example, converting

25

into

–25

):

var iNum= 25;

iNum = -iNum;

alert(iNum); //outputs “-25”

Similar to unary plus, unary minus converts a string into a number with one slight difference: Unary

minus also negates the value. For example:

var sNum = “25”;

alert(typeof sNum); //outputs “string”

var iNum = -sNum;

alert(iNum); //outputs “-25”

alert(typeof iNum); //outputs “number”

36

Chapter 2

05_579088 ch02.qxd 3/28/05 11:35 AM Page 36

Free JavaScript Editor
Ajax Editor

©

↓