How to code numeric and string expressions
An expression can be as simple as a single value or it can be a series of operations that result in a single value. In figure 2-8, you can see the operators for coding both numeric and string expressions. If you've programmed in another language, these are probably similar to what you've been using. In particular, the first four arithmetic operators are common to most programming languages.
Most modern languages also have a modulus, or mod, operator that calculates the remainder when the left value is divided by the right value. In the example for this operator, 13 % 4 means the remainder of 13 / 4. Then, since 13 / 4 is 3 with a remainder of 1, 1 is the result of the expression.
One of the common uses of the mod operator is determining if a number is even or odd. For instance, any number % 2 will return 0 if the number is even and 1 if the number is odd. Another use is determining if a year is a leap year. If, for example, year % 4 returns 0, then year is divisible by 4.
In contrast to the first five operators in this figure, the increment and decrement operators add or subtract one from a variable. If you aren't already familiar with these operators, you'll see them illustrated later in this book.
When an expression includes two or more operators, the order of precedence determines which operators are applied first. This order is summarized in the table in this figure. For instance, all multiplication and division operations are done from left to right before any addition and subtraction operations are done.
To override this order, though, you can use parentheses. Then, the expressions in the innermost sets of parentheses are done first, followed by the expressions in the next sets of parentheses, and so on. This is typical of all programming languages, and the examples in this figure show how this works.
The one operator that you can use with strings is the concatenation operator. This operator joins two strings with no additional characters between them.
Since the plus sign is used for both addition and concatenation, JavaScript has to look at the data type of the values to determine whether it should add or concatenate the values. If both values are numbers, JavaScript adds them together. If both values are strings, JavaScript concatenates them. And if one value is a string and the other is a number, JavaScript converts the number to a string and then concatenates the two values.
Common arithmetic operators
The order of precedence for arithmetic expressions
Examples of precedence and the use of parentheses
3 + 4 * 5 // Result is 23 since the multiplication is done first(3 + 4) * 5 // Result is 35 since the addition is done first13 % 4 + 9 // Result is 10 since the modulus is done first13 % (4 + 9) // Result is 0 since the addition is done first
The concatenation operator for strings
Description
Figure 2-8 How to code numeric and string expressions