↑

Main Page

# Subtract

Just like the multiplicative operators, additive operators also behave in special ways when dealing with

special values. If the two operands are numbers, they perform an arithmetic add and return the result

according to these rules:

?

If either number is

NaN

, the result is

NaN

.

?

If

Infinity

is added to

Infinity

, the result is

Infinity

.

?

If –

Infinity

is added to –

Infinity

, the result is –

Infinity

.

?

If

Infinity

is added to –

Infinity

, the result is

NaN

.

?

If +0 is added to +0, the result is +0.

?

If –0 is added to +0, the result is +0.

?

If –0 is added to –0, the result is –0.

If, however, one of the operands is a string, then the following rules are applied:

?

If both operands are strings, the second string is concatenated to the first.

?

If only one operand is a string, the other operand is converted to a string and the result is the

concatenation of the two strings.

For example:

var result1 = 5 + 5; //two numbers

alert(result); //outputs “10”

var result2 = 5 + “5”; //a number and a string

alert(result); //outputs “55”

This code illustrates the difference between the two modes for the add operator. Normally,

5 + 5

equals

10

(a primitive number value), as illustrated by the first two lines of code. However, if one of the operands

is changed to a string,

“5”

, the result becomes

“55”

(which is a primitive string value) because the first

operand gets translated to

“5”

as well.

Subtract

The subtract operator (–) is another that is used quite frequently:

var iResult = 2 – 1;

Just like the add operator, the subtract operator has special rules to deal with the variety of type conver-

sions present in ECMAScript:

?

If the two operands are numbers, perform arithmetic subtract and return the result.

?

If either number is

NaN

, the result is

NaN

.

To avoid one of the most common mistakes made in JavaScript, always double check

the data types when using the add operator.

48

Chapter 2

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

Free JavaScript Editor
Ajax Editor

©

↓