Back on game night, you wrote score = score + 10 and watched JavaScript work out the right side before moving the name. In the last lesson, you chose const for names that never move and let for names that do. So far, your calculations have used a plus sign between two numbers.
Everyday questions need a bit more, like how many slices each guest gets or how long an evening of board games takes. In this lesson, you’ll predict what a calculation with several operators gives, and then turn a short problem description into calculations of your own. You’ll check each prediction in the Node REPL or a small script.
Try the Arithmetic Operators in the REPL
A quick calculation is a good job for the Node REPL. Open the integrated terminal in your course folder, type node, and press Enter. At the > prompt, the REPL shows the value of each expression you type.
JavaScript has six arithmetic operators, the symbols that calculate with numbers:
| Operator | Meaning | Example |
|---|---|---|
+ |
Addition | 7 + 2 |
- |
Subtraction | 7 - 2 |
* |
Multiplication | 7 * 2 |
/ |
Division | 7 / 2 |
% |
Remainder | 7 % 2 |
** |
Power | 7 ** 2 |
The * stands in for the times sign on a calculator. Division, remainder, and powers deserve a closer look before you use them.
Division never chops off the part after the decimal point, so 7 / 2 gives 3.5, not 3. JavaScript has one number type for whole numbers and decimal numbers alike.
The remainder operator % answers a different question: What’s left over after you share out as many whole times as possible? Seven cookies shared between two people give each person three cookies, and one is left over, so 7 % 2 gives 1.
The ** operator raises a number to a power, so 7 ** 2 is seven times seven, or 49.
Now apply these to new numbers. Write down what you expect each expression to give, then type them at the prompt to check:
> 6 * 4
24
> 9 / 4
2.25
> 9 % 4
1
> 3 ** 3
27
Nine cookies between four people give each two, with 1 left over. The expression 3 ** 3 is three times three times three.
A few symbols you may know from other tools mean something different in JavaScript:
^isn’t a power operator.2 ^ 3runs without an error but gives1, because^does something unrelated to powers. Use**.%isn’t percent. It always means remainder.//isn’t division. Two slashes start a comment, so JavaScript ignores the rest of the line.- Spreadsheet habits don’t carry over. There’s no
=in front of a calculation,xisn’t times, and a number like1250has no comma in it.