</>
Skip to content
JavaScript lessons (12/64)

JavaScript — Arithmetic

The seven operators

let a = 10, b = 3;

a + b    // 13    add
a - b    // 7     subtract
a * b    // 30    multiply
a / b    // 3.3333…  divide
a % b    // 1     remainder after division
a ** b   // 1000  power (10³)

% — the underrated one

Remainder answers "is it divisible?" instantly:

n % 2 === 0        // even?
i % 2              // 0=even row, 1=odd row (zebra tables!)
minutes % 60       // leftover minutes past full hours
items.length % 3   // how many overflow the last row of 3

++ and --

let lives = 3;
lives++;   // 4 — add one
lives--;   // 3 — remove one

Two flavors exist (++x vs x++ — returns new vs old value), but in modern code you'll almost always see them as standalone statements where they behave identically.

Order of operations

Math rules apply; parentheses win:

2 + 3 * 4       // 14
(2 + 3) * 4     // 20
2 ** 3 ** 2     // 512 — powers go right-to-left!

When expression order isn't obvious at a glance, add parentheses even if redundant — free documentation.

The floating-point surprise

0.1 + 0.2            // 0.30000000000000004  😱
0.1 + 0.2 === 0.3    // false

Computers store decimals in binary; tiny representation errors leak into decimal math. Every language with IEEE floats does this — JS just doesn't hide it.

Practical fixes:

(0.1 + 0.2).toFixed(2)          // "0.30" — display formatting
Math.round((0.1+0.2) * 100)/100 // 0.3   — rounding before comparing

Money? Store cents as integers. Always.

Numbers from text

"5" + 1      // "51"  ← plus means CONCATENATION when a string is present!
"5" - 1      // 4     ← minus forces number conversion 😵

That asymmetry is the most infamous JS gotcha. Convert deliberately:

Number("5") + 1    // 6
+"5" + 1           // 6 — unary plus shortcut
parseInt("42px")   // 42 — stops at first non-digit

Mini Practice

  1. Compute all seven operators on 17 and 5; predict before running
  2. Use % to print whether loop counters 1–15 are odd or even
  3. Reproduce 0.1+0.2; fix display with toFixed and comparison with rounding
  4. Explain "5"+1 vs "5"-1 in one comment line each
  5. Build seconds→mm:ss converter using / and % together

Next: assignment →

Related Topics

Frequently Asked Questions about Arithmetic

What is Arithmetic in JavaScript?

Arithmetic is a fundamental concept in JavaScript. This lesson explains it step by step with clear examples, making it easy for beginners to understand.

How do I learn Arithmetic?

Start by reading the explanation above, then try the code examples. Practice by modifying the examples and experimenting with different values. Hands-on practice is the best way to learn Arithmetic.

Why is Arithmetic important in JavaScript?

Arithmetic is essential for JavaScript development. Understanding this concept will help you write better code and solve real-world problems more effectively.