One number type
Nearly every program computes something — prices at checkout, scores in a game, minutes left on a timer — so arithmetic is the first tool to move over from Python. The good news: it transfers almost unchanged, with one operator missing and one type merged.
Python has separate int and float types. JavaScript has just one: number. Both 5 and 5.5 are numbers, and division always gives you the exact decimal result.
The operators match Python almost exactly:
| Operation | Python | JavaScript |
|---|---|---|
| add, subtract, multiply | + - * | + - * |
| division | / | / |
| remainder (modulo) | % | % |
| power | ** | ** |
| floor division | // | Math.floor(a / b) |
The one to remember: JavaScript has no // operator. To divide and drop the decimal part, divide normally and round down with Math.floor(...).
Code exercise · javascript
Predict each line before you run it. The third line is the remainder of 7 divided by 2, and the last uses Math.floor to copy Python's 7 // 2.
The Math toolbox
Math is a built-in object full of helpers, like Python's math module but always available with no import:
Math.floor(3.9)→ 3 (round down)Math.round(3.5)→ 4 (round to nearest)Math.abs(-8)→ 8 (absolute value)Math.max(2, 9, 4)→ 9 andMath.min(2, 9, 4)→ 2Math.sqrt(81)→ 9 (square root, √81)
You call them with a dot, Math.floor(x), because they live on the Math object. Objects get a full treatment in unit 5.
Code exercise · javascript
Your turn. A timer holds 400 seconds. Print the whole minutes (400 divided by 60, rounded down) on the first line and the leftover seconds (the remainder) on the second line.
Code exercise · javascript
Second practice. A restaurant bill is 50 and the tip rate is 0.2 (20%). Print the tip amount on the first line and the bill plus tip on the second, using math on the two variables (no hand-typed answers).
Quiz
In Python, 7 // 2 gives 3. Which JavaScript expression gives the same result?