Skip to content
Topic 4 of 16
Theory

Maths and comparison

Why it matters

Almost any program calculates something: an order total, the time until the lesson ends, game points, discount percentages. Programs also constantly compare: is there enough money, is the password right, is time up. This topic gives you all the tools for that.

Arithmetic

console.log(7 + 2);   // 9   addition
console.log(7 - 2);   // 5   subtraction
console.log(7 * 2);   // 14  multiplication
console.log(7 / 2);   // 3.5 division — a decimal!
console.log(7 % 2);   // 1   remainder
console.log(2 ** 10); // 1024 exponent

The order of operations is as in maths: first **, then *, /, %, then + and -. Parentheses change the order: (2 + 3) * 4 → 20, while 2 + 3 * 4 → 14.

The remainder %

A very useful operator:

  • n % 2 === 0 — the number is even;
  • n % 10 — the last digit of a number (1234 % 10 → 4);
  • total % 60 — the minutes left over the full hours.
const seconds = 200;
console.log(Math.floor(seconds / 60), "min", seconds % 60, "sec");

Output:

3 min 20 sec

The Math object

Math is a built-in set of maths functions:

console.log(Math.round(4.5));  // 5   by normal rules
console.log(Math.floor(4.9));  // 4   down
console.log(Math.ceil(4.1));   // 5   up
console.log(Math.trunc(-4.7)); // -4  drop the fractional part
console.log(Math.max(3, 9, 2)); // 9
console.log(Math.min(3, 9, 2)); // 2
console.log(Math.abs(-8));     // 8   absolute value
console.log(Math.sqrt(81));    // 9   square root
console.log(Math.random());    // random from 0 to 1, e.g. 0.4271…

A random integer from 1 to 6 (a die): Math.floor(Math.random() * 6) + 1.

Decimals and precision

console.log(0.1 + 0.2);

Output:

0.30000000000000004

That's not a JavaScript bug — almost all languages store decimals like this. For money, count in cents (whole numbers) or round the result: Number((0.1 + 0.2).toFixed(2)) → 0.3. The toFixed(2) method returns a string with two digits after the point.

Comparison

A comparison gives a boolean value, true or false:

console.log(5 > 3);    // true
console.log(5 < 3);    // false
console.log(5 >= 5);   // true  greater than or equal
console.log(4 <= 3);   // false less than or equal
console.log(5 === 5);  // true  strictly equal
console.log(5 !== 3);  // true  not equal

Strict === and loose ==

console.log(5 === "5"); // false — different types
console.log(5 == "5");  // true  — == converts types first
console.log(0 == "");   // true  — surprise!

== tries to convert values to one type and gives strange results. Always use === and !==.

Strings are compared alphabetically, or more precisely by character codes: "apple" < "banana" → true, and "Z" < "a" → true, because capital letters come before lowercase ones.

How it works inside

All numbers in JavaScript are stored in one format — a 64-bit floating-point number (the IEEE 754 standard). That's why 7 / 2 gives 3.5 and not 3 as in some other languages, and why 0.1 + 0.2 isn't exactly 0.3: the decimal 0.1 can't be written exactly in binary, just as 1/3 can't be written exactly as a decimal. Division by zero doesn't break the program: 5 / 0 → Infinity.

Common mistakes

  1. Expecting a whole number from division. 7 / 2 → 3.5. For a whole number — Math.floor(7 / 2).
  2. = instead of ===. if (x = 5) doesn't compare, it assigns. Comparison is ===.
  3. == instead of ===. 0 == "" → true. Write ===.
  4. Rounding with the wrong function. Math.round — by the rules, Math.floor — down, Math.ceil — up. For "how many boxes are needed" — ceil; for "how many full hours" — floor.
  5. toFixed returns a string. (1.5).toFixed(2) + 1 → "1.501". Wrap it in Number(...).

Cheat sheet

What How
Operators + - * / % **
Remainder, evenness n % 2 === 0
Rounding Math.round, Math.floor, Math.ceil, Math.trunc
Maximum / minimum Math.max(a, b), Math.min(a, b)
Absolute value, root Math.abs(x), Math.sqrt(x)
Random Math.random() — from 0 to 1
Digits after the point x.toFixed(2) → a string
Comparison > < >= <= === !==

Hours and minutes

Easy+10 XP

A film lasts minutes = 135 minutes. Create:

  • hours — how many full hours (2);
  • rest — how many minutes are left over the full hours (15).

Calculate them from minutes instead of typing the answers.

Connect the connector to solve tasks

Task code runs on your own computer — faster and more reliable than in the browser. This needs the free CodeWithMe connector app. You only connect it once.

Looking for the connector on this computer…

  1. 1
    Download the connector for your system (Windows, macOS or Linux).Download the connectorOn the download page pick the file with your system in its name, e.g. windows-amd64.
  2. 2Run it and choose a folder for your solutions. It will install Python and Node.js there by itself when needed.
  3. 3
    Enter below the 6-digit code shown in the connector window (“Code for CodeWithMe”). If the browser asks about local network access — allow it.

The connector is open source (on GitHub), works only on your computer and runs code only after you enter the pairing code.