Operators That Add and Subtract
These seem simple at first but there are a few surprises.
The Additive Operators¶
In math, additive refers to both addition and subtraction. You can think of subtraction as just adding with negative numbers.
The plus sign + is used for math addition and string concatenation.
The minus sign - is used for math subtraction.
Using the Additive Operators¶
Adding and Subtracting Directly into Variables.¶
1 2 3 4 5 6 7 8 9 10 11 12 | |
Adding and Subtracting with Variables¶
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 | |
Concatenation of strings.¶
The plus sign + is also used for concatenation
Concatenation, or combining string to form a new longer string. Notice that the <br /> tags are being concatenated too.
1 2 3 4 5 6 7 8 9 10 11 12 13 | |
Concatenation of Strings and Numbers.¶
When the plus sign has one string to its left OR right and a number on the other side, the number will be converted to a string and concatenated to the string.
1 2 3 4 5 6 7 8 9 10 | |
Concatenation when you don't expect it!.¶
When you have a string that contains just numbers and you try to add it to a true number JavaScript will concatenate it and not do addition.
1 2 3 4 5 6 7 8 9 10 11 12 | |
Converting from a string to a number.¶
When you have a string that contains a valid number, you can convert it to a number. We use the Number() function for this.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 | |
New Coding Standard
Refer to the Coding standards regarding specifics
Note standards regarding caclulations and the use of document.write
Labs
- Lab04: Additive Operators
- unit02/labs/lab-04-additiveOperators.html
Exercises
- Exercise for lab04
- unit02/exercises/exercise-04.html