Lesson 3 of 22 Β· 8 min Β· 3 hands-on steps
Numbers & Math
Use JavaScript as a calculator, including the remainder operator programmers love.
JavaScript is a calculator
| Operator | Meaning | Example | Result |
|---|---|---|---|
+ |
add | 5 + 2 |
7 |
- |
subtract | 5 - 2 |
3 |
* |
multiply | 5 * 2 |
10 |
/ |
divide | 5 / 2 |
2.5 |
% |
remainder | 5 % 2 |
1 |
** |
power | 5 ** 2 |
25 |
Try them all. Change the numbers and run again:
Order of operations
Just like school math: parentheses first, then **, then * / %, then + -.
When in doubt, add parentheses. They make your intention obvious to the next reader too.
The remainder operator %
% looks strange, but you'll use it a lot:
Decimals can surprise you
That's not a bug in JavaScript. Computers store decimals in binary, and some numbers can't be stored exactly (like 1/3 in decimal). For money, developers often count in cents (whole numbers) instead.
π§ͺ Practice: 3 steps
0 / 3 doneStep 1 of 3 Β· Minutes in a week
Print how many minutes are in a week. Let the computer do the math: 7 days Γ 24 hours Γ 60 minutes.
Output appears here. Press Run or Ctrl/β + Enter.
Step 2 of 3 Β· Even or odd?
The remainder operator % gives what's left over after dividing. 10 % 3 is 1.
Print the remainder of 17 divided by 2. (If it's 1, the number is odd!)
Output appears here. Press Run or Ctrl/β + Enter.
Step 3 of 3 Β· Order of operations
This should print the average of 80 and 90, which is 85, but it prints the wrong number. Add parentheses to fix it.
Output appears here. Press Run or Ctrl/β + Enter.
β Check your understanding
What is 10 % 4?
What does 2 + 3 * 4 equal in JavaScript?
Create a free account to track your progress.