JavaScript Basics · Lesson 3 of 13

Numbers and Math

JavaScript is a capable calculator. These are the arithmetic operators:

OperatorMeaningExampleResult
+add7 + 29
-subtract7 - 25
*multiply7 * 214
/divide7 / 23.5
%remainder7 % 21
**to the power of7 ** 249

Multiplication and division happen before addition and subtraction, as in school. Use brackets to change the order:

console.log(2 + 3 * 4);     // 14
console.log((2 + 3) * 4);   // 20

The remainder operator % gives what is left over after dividing. It is more useful than it looks: n % 2 is 0 for every even number.

Variables in calculations

Variables can be used anywhere a number can:

const price = 20;
const quantity = 3;
const total = price * quantity;

Updating a variable

To change a variable based on its current value, there are shortcuts:

let points = 10;
points += 5;    // same as points = points + 5
points -= 2;    // same as points = points - 2
points++;       // add exactly 1

Rounding

Math.round(4.6) gives 5. Math.floor(4.6) always rounds down to 4, and Math.ceil(4.2) always rounds up to 5.

Your Task

  1. A pizza costs 12 and you order 3. Create a variable subtotal from price * pizzas.
  2. Create tip as 15 percent of the subtotal (multiply by 0.15).
  3. Create total as the subtotal plus the tip.
  4. Four friends share the bill. Create perPerson as the total divided by friends, rounded with Math.round.
  5. Print total and perPerson, each with its own console.log.
  • subtotal is 36, calculated from the variables
  • tip is 15 percent of the subtotal
  • total is the subtotal plus the tip
  • perPerson is the total divided by four, rounded
  • The total and the amount per person are printed