JavaScript is actually also a high-powered calculator. Adding up scores, working out prices, counting up and down—whenever you deal with numbers, calculations are bound to come up. They’re easy to write. It’s almost the same as the arithmetic you already know.
Let’s write some
console.log(1 + 2);
console.log(10 - 4);
console.log(3 * 5);
console.log(10 / 2);The console shows 3, 6, 15, and 5.
| Symbol | Meaning | In arithmetic |
|---|---|---|
+ | Addition | + |
- | Subtraction | − |
* | Multiplication | × |
/ | Division | ÷ |
× and ÷ are awkward to type on a keyboard, so in the world of programming there’s a convention to use * (asterisk) and / (slash) instead.
Combining with variables
The real power of calculations comes out when you combine them with variables.
let age = 3;
console.log(age + 1);The console shows 4. “Take the contents out of the box and add 1”—the variable’s name becomes the ingredient for the calculation as-is.
let price = 150;
let count = 3;
console.log(price * count);Buy 3 apples at 150 yen each? The answer 450 shows up. Even when the values change, the formula stays the same—this is the joy of calculating with a program.
Putting the result back into a box
You can also store the result of a calculation back into a variable.
let count = 0;
count = count + 1;The second line means “add 1 to the current count (0), and put it back into count.” This makes count become 1. The mechanism behind “the number goes up every time you press Like” is exactly this.
There’s also “addition” for text
+ alone can be used with text too. When you join text with text using +, they get stuck together into one piece of text.
let name = "Shima";
console.log("Hello, " + name + "!");The console shows “Hello, Shima!” Slotting a name into a greeting—this is how you use it to build up sentences.
Summary of this lesson
- Write calculations with the four symbols
+-*/(*= multiply,/= divide) - You can use variables as ingredients for calculations, and store the result back into a variable
+can be used with text too, and text joined with text gets stuck together