Operators

Operators in JavaScript, as in PHP, can involve mathematics, changes to strings, and comparison and logical operations (and, or, etc.). JavaScript mathematical operators look a lot like plain arithmetic; for instance, the following statement outputs 15:

document.write(13 + 2)

The following sections introduce the various operators.

Arithmetic Operators

Arithmetic operators are used to perform mathematics. You can use them for the main four operations (addition, subtraction, multiplication, and division), as well as to find the modulus (the remainder after a division) and to increment or decrement a value (see Table 13-2).

The assignment operators are used to assign values to variables. They start with the very simple, =, and move on to +=, -= , and so on. The operator += adds the value on the right side to the variable on the left, instead of totally replacing the value on the left. Thus, if count starts with the value 6, the statement:

count += 1

sets count to 7, just like the more familiar assignment statement:

count = count + 1

Table 13-3 lists the various assignment operators available.

Comparison operators are generally used inside a construct such as an if statement where you need to compare two items. For example, you may wish to know whether a variable you have been incrementing has reached a specific value, or whether another variable is less than a set value, and so on (see Table 13-4).

Unlike with PHP, JavaScript’s logical operators do not include and and or equivalents to && and ||, and there is no xor operator. The available operators are listed in Table 13-5.

The following forms of post- and pre-incrementing and -decrementing you learned to use in PHP are also supported by JavaScript:

++x
−−y
x += 22
y −= 3

JavaScript handles string concatenation slightly differently from PHP. Instead of the . (period) operator, it uses the plus sign (+), like this:

document.write("You have " + messages + " messages.")

Assuming that the variable messages is set to the value 3, the output from this line of code will be:

You have 3 messages.

Just as you can add a value to a numeric variable with the += operator, you can also append one string to another the same way:

name =  "James"
name += " Dean"

Escape characters, which you’ve seen used to insert quotation marks in strings, can also be used to insert various other special characters, such as tabs, newlines, and carriage returns. Here is an example using tabs to lay out a heading; it is included here merely to illustrate escapes, because in web pages there are better ways to do layout:

heading = "Name\tAge\tLocation"

Table 13-6 details the escape characters available.