Calculating with Arithmetic Operators
Introduction
Welcome back to Storing and Calculating with JavaScript Values! In the previous lesson we taught a variable to change, and along the way we wrote our first tiny calculation: cupsSold + 2. That single + was doing something we have not looked at properly yet - it was asking JavaScript to work out a new number for us.
Calculating is one of the things computers do best, and in this lesson we give JavaScript the full set of tools for it. We will learn how to:
- Add, subtract, multiply, and divide with the four arithmetic operators.
- See how JavaScript works an expression out to a single value before printing or storing it.
- Predict which part of a longer calculation happens first.
- Use parentheses to take control of that order.
By the end, we will have a program that works out an order total, the change from a 20-dollar bill, and a fair share per person - without doing any of the arithmetic ourselves.
The Four Operators
An operator is a symbol that tells JavaScript to do something with the values on either side of it. The four we need today are the ones we already know from school, with two small changes in how they are written:
+adds, exactly as we would expect.-subtracts.*multiplies. There is no × key on a keyboard, so programming languages use the asterisk instead./divides. Likewise, the forward slash stands in for ÷.
Each operator sits between two numbers, and the two numbers together with the operator - 12 + 8, say - are called an expression. An expression is anything that JavaScript can work out to a single value.
An Expression Becomes One Value
Let's give console.log an expression instead of a plain number and see what it prints:
Before it prints anything, JavaScript works each expression out - 12 + 8 becomes 20, and so on - and what we see is the finished value, never the sum itself:
Two things are worth noticing. First, 12 + 8 is nowhere in the output; the expression is replaced by its result. Second, division happily produces a number with a decimal point when the numbers do not divide evenly: 7 / 2 is 3.5, not 3 with something left over. JavaScript treats 3.5 and 20 as the same kind of value - a number - so we can mix them freely.
