JavaScript is a capable calculator. These are the arithmetic operators:
| Operator | Meaning | Example | Result |
|---|---|---|---|
+ | add | 7 + 2 | 9 |
- | subtract | 7 - 2 | 5 |
* | multiply | 7 * 2 | 14 |
/ | divide | 7 / 2 | 3.5 |
% | remainder | 7 % 2 | 1 |
** | to the power of | 7 ** 2 | 49 |
Multiplication and division happen before addition and subtraction, as in school. Use brackets to change the order:
console.log(2 + 3 * 4); // 14
console.log((2 + 3) * 4); // 20
The remainder operator % gives what is left over after dividing. It is more useful than it looks: n % 2 is 0 for every even number.
Variables in calculations
Variables can be used anywhere a number can:
const price = 20;
const quantity = 3;
const total = price * quantity;
Updating a variable
To change a variable based on its current value, there are shortcuts:
let points = 10;
points += 5; // same as points = points + 5
points -= 2; // same as points = points - 2
points++; // add exactly 1
Rounding
Math.round(4.6) gives 5. Math.floor(4.6) always rounds down to 4, and Math.ceil(4.2) always rounds up to 5.
Your Task
- A pizza costs 12 and you order 3. Create a variable
subtotalfromprice * pizzas. - Create
tipas 15 percent of the subtotal (multiply by0.15). - Create
totalas the subtotal plus the tip. - Four friends share the bill. Create
perPersonas the total divided byfriends, rounded withMath.round. - Print
totalandperPerson, each with its ownconsole.log.
subtotalis36, calculated from the variablestipis 15 percent of the subtotaltotalis the subtotal plus the tipperPersonis the total divided by four, rounded- The total and the amount per person are printed
Lesson complete!
Next Lesson: Strings