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,
is equal to
because the expression evaluates to 2 + 20. The variable
is also equal to
, although it evaluates 1 + 21 because the increment and decrement aren’t com-
pleted until after the value of
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
, 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
into the actual number. When the unary plus operates
on strings, it evaluates strings the same way as
with one major difference: Unless the string
begins with
(indicating a hexadecimal number), the string is converted as if it were decimal. So
is always 10 when converted using unary plus, however,
is converted to 11.
The unary minus, on the other hand, negates the value of a number (for example, converting
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”
Chapter 2
05_579088 ch02.qxd 3/28/05 11:35 AM Page 36

JavaScript EditorFree JavaScript Editor     Ajax Editor