Arithmetic and Assignment
JavaScript does math in the same order as school math. * and / come before + and -, and parentheses change the order:
console.log(2 + 3 * 4);
console.log((2 + 3) * 4);
Output:
14
20
The operators are +, -, *, /, % and **. The % operator gives the remainder after division. For example, 10 % 3 is 1, because 10 divided by 3 is 3 with 1 left over.
Division in JavaScript always gives the exact answer, so you need a different tool when you want a whole number. JavaScript has a built-in object called Math with many math functions. Math.floor rounds down to a whole number. Together with %, it can split a value into parts:
const minutes = 130;
console.log(minutes / 60);
console.log(Math.floor(minutes / 60));
console.log(minutes % 60);
console.log(Math.round(2.5), Math.ceil(2.1));
Output:
2.1666666666666665
2
10
3 3
130 minutes is 2 hours and 10 minutes. Math.round rounds to the nearest whole number, and Math.ceil always rounds up. You will use % a lot later. For example, n % 2 is 0 when n is even.
Changing a variable
Programs often take a variable, change it, and store the result back. JavaScript has short operators for this:
let balance = 100;
balance += 50;
balance -= 20;
console.log(balance);
let count = 0;
count++;
count++;
console.log(count);
Output:
130
2
balance += 50 means balance = balance + 50. There is one for each operator: -=, *=, /= and so on. count++ adds exactly 1, and count-- takes away 1. Write count++ on a line by itself. Inside a bigger expression it is easy to misread.
All of these change the variable, so the variable must be declared with let. Counters and running totals are exactly where let belongs.
In the exercise, read two numbers and print six results, including one with Math.floor.