Arithmetic Operations and Division
One kind of number
JavaScript has exactly one number type. There is no separate whole-number type and decimal type the way some other languages have. 7 and 7.5 are both just numbers.That single type changes what you see on screen. A result that lands on a whole number prints as a whole number, with nothing after the decimal point, even when you wrote a decimal point in the code.
The arithmetic operators
These are all of them. You have met most of them in math class already.| Operator | Name | Example |
|---|---|---|
a + b | Addition | 3 + 10 is 13 |
a - b | Subtraction | 3 - 10 is -7 |
a * b | Multiplication | 3 * 10 is 30 |
a / b | Division | 3 / 10 is 0.3 |
a % b | Remainder | 13 % 10 is 3 |
a ** b | Exponent | 3 ** 2 is 9 |
-a | Negation | flips the sign of a |
This set is about the four you already know, and about what JavaScript does when a division does not come out even. The remainder operator and exponents each get a set of their own later in this unit.
Division never truncates
The single slash always hands back the full quotient, fraction and all. It does not round, and it does not chop anything off. If the division does not come out even, you get the decimal.Getting the whole part
When you want the whole part and nothing else, you have to ask for it. Math.floor takes a number and gives back the largest whole number that is not above it.Math.floor and Math.trunc part company on negatives
Math.trunc also hands back a whole number, and on a positive value the two agree every single time. On a negative value they do not. Math.floor moves DOWN the number line. Math.trunc moves TOWARD zero. For a negative number, down and toward zero are opposite directions.| Expression | Prints | Why |
|---|---|---|
Math.floor(7 / 2) | 3 | 3.5 moved down the number line |
Math.trunc(7 / 2) | 3 | 3.5 chopped toward zero, same landing spot |
Math.floor(-7 / 2) | -4 | -3.5 moved down, which is away from zero |
Math.trunc(-7 / 2) | -3 | -3.5 chopped toward zero |
The program below divides the height a path climbs by the minutes the walk takes, and prints the exact quotient and what
Math.floor and Math.trunc make of it. Run it, then change it and run it again:• Set
minutes to 4.0.• Set
climb to -33, for a path that goes downhill.• Set
minutes to 3.let climb = 33;
let minutes = 4;
console.log("Per minute:", climb / minutes);
console.log("Math.floor gives", Math.floor(climb / minutes));
console.log("Math.trunc gives", Math.trunc(climb / minutes));
Output
Press Run to see what this program prints.
Note: This IDE is for experimenting with the code in this lesson. Your changes are not saved, and refreshing the page puts back the original lesson code.