Lesson ยท 8 min
Numbers and math
Numbers
JavaScript has one kind of number. It can be a whole number such as 12, or a decimal number such as 4.8. You write a number without quotation marks.
Operators
An operator is a symbol that does something with values.
| Operator | What it does | Example | Result |
|---|---|---|---|
+ |
add | 7 + 2 |
9 |
- |
subtract | 7 - 2 |
5 |
* |
multiply | 7 * 2 |
14 |
/ |
divide | 7 / 2 |
3.5 |
% |
remainder after division | 7 % 2 |
1 |
** |
power | 7 ** 2 |
49 |
JavaScript does multiplication and division before addition and subtraction. Use parentheses to change the order: (1 + 2) * 3 is 9, and 1 + 2 * 3 is 7.
const width = 4;
const height = 3;
const area = width * height;
console.log(area);
The Math object
Math has functions for common jobs.
Math.round(4.6)gives5. It rounds to the nearest whole number.Math.floor(4.6)gives4. It rounds down.Math.ceil(4.2)gives5. It rounds up.Math.max(3, 9, 5)gives9. It finds the largest value.
Your turn
Do the five tasks in order. Each task is checked on its own.
Tasks
5 to do
Task 1, not checked yet. Make a constant
pricewith the number12, and a constantcountwith the number5. Then make a constantsubtotalthat ispricemultiplied bycount.Task 2, not checked yet. Make a constant
taxthat is8%ofsubtotal. Then make a constanttotalthat issubtotalplustax.Task 3, not checked yet. Share
17items among5people. Make a constantleftoverwith the number of items that remain. Use the remainder operator%.Task 4, not checked yet. Make a constant
wholethat istotalrounded down to a whole number. UseMath.floor.Task 5, not checked yet. Print the sentence
Total: 64.8withconsole.log. Build it with a template string that usestotal.
Task 1 of 5
Make a constant price with the number 12, and a constant count with the number 5. Then make a constant subtotal that is price multiplied by count.