JavaScript Roadmap — Day 7: Arithmetic Operators

 

JavaScript · Day 7 of 180 · Beginner Phase

Arithmetic Operators

The building blocks of every calculation in JavaScript — and the hidden behaviors that trip up every beginner.

Day 7 / 180
Beginner Phase

Look at this code. A developer is building a shopping cart. Can you spot the bug before reading on?

JavaScript — Can you find the bug?
const price    = 500;
const tax      = 50;
const discount = 2;

const total = price + tax * discount;
console.log(total); // Developer expects 1100
                      // JavaScript gives 600
                      // WHY?!

The answer:

JavaScript calculated tax * discount first (50 × 2 = 100), then added price (500 + 100 = 600). The developer forgot that multiplication runs before addition. The fix is simple: (price + tax) * discount. This is operator precedence — and it is the source of real bugs in real projects every single day.

In this lesson you will learn all 7 arithmetic operators deeply — including the hidden behaviors that most tutorials completely skip. By the end you will never write a wrong calculation again.

1. The 7 Arithmetic Operators

JavaScript gives you exactly 7 arithmetic operators. Five of them you already know from school. Two of them — % and ** — are unique to programming and deserve their own deep sections below.

JavaScript — All 7 operators
const a = 10, b = 3;

console.log(a + b);   // 13   — addition
console.log(a - b);   // 7    — subtraction
console.log(a * b);   // 30   — multiplication
console.log(a / b);   // 3.333.. — division
console.log(a % b);   // 1    — remainder (leftover)
console.log(a ** b);  // 1000 — exponentiation (10³)
console.log(-a);      // -10  — unary negation
Operator Name Example Result Real use
+Addition5 + 38Totals, scores
-Subtraction5 - 32Discounts, balance
*Multiplication5 * 315Area, quantity × price
/Division10 / 33.333Averages, ratios
%Remainder10 % 31Even/odd, cycles
**Exponentiation2 ** 8256Powers, growth
-xUnary negation-5-5Flip sign

2. Operator Precedence — Who Goes First?

When you write an expression with multiple operators JavaScript has rules for which one runs first. This is called operator precedence — and it is exactly the same as the BODMAS/PEMDAS rules you learned in school. Most developers forget it exists until it causes a bug.

The order from highest to lowest priority:

Priority Operator Runs
1st — Highest( )Brackets always first
2nd**Exponentiation
3rd* / %Multiply, divide, remainder
4th — Lowest+ -Addition and subtraction
JavaScript — Precedence examples
// * runs before +
console.log(2 + 3 * 4);      // 14 not 20
console.log((2 + 3) * 4);    // 20 — brackets change everything

// ** runs before *
console.log(2 * 3 ** 2);      // 18 — (3**2=9, 2*9=18)
console.log((2 * 3) ** 2);    // 36 — (2*3=6, 6**2=36)

// Left to right for same priority
console.log(10 - 3 - 2);      // 5 — (10-3=7, 7-2=5)
console.log(10 / 2 * 5);      // 25 — (10/2=5, 5*5=25)

🔥 Professional habit: When in doubt — always use brackets. (price + tax) * quantity is clearer than relying on precedence rules. Brackets cost nothing and prevent every precedence bug forever.

3. Increment ++ and Decrement --

++ adds 1 to a variable. -- subtracts 1. Simple. But where you put them — before or after the variable — changes what value is returned. This is one of the most common JavaScript interview questions and a real source of bugs.

JavaScript — prefix vs postfix
// POSTFIX — use first, then add
let x = 5;
console.log(x++); // 5 ← returns OLD value
console.log(x);    // 6 ← now x is updated

// PREFIX — add first, then use
let y = 5;
console.log(++y); // 6 ← returns NEW value
console.log(y);    // 6

// In a real expression — this is where it matters
let a = 5;
let b = a++ * 2; // b = 10 (uses 5), a becomes 6

let c = 5;
let d = ++c * 2; // d = 12 (uses 6), c is 6

// In simple loops — both work the same
for(let i = 0; i < 3; i++) { // i++ or ++i — same result here
  console.log(i);
}

💡 Simple rule: In a plain loop like i++ — prefix and postfix make no difference. The difference only matters when you use the value in the same expression. When in doubt — do the increment on its own line and keep the code readable.

4. The % Remainder Operator — More Powerful Than You Think

The % operator gives you the leftover after dividing two numbers. It looks simple but it solves problems that would otherwise take 5 lines of code to write. Every JavaScript developer uses it constantly.

JavaScript — % in real use cases
// Check even or odd — most common use
console.log(10 % 2); // 0 — even (no remainder)
console.log(7 % 2);  // 1 — odd
console.log(0 % 2);  // 0 — even (0 is even!)

// Cycle through values — wrap around
let slides = ["A", "B", "C"];
let i = 0;
console.log(slides[i++ % slides.length]); // A
console.log(slides[i++ % slides.length]); // B
console.log(slides[i++ % slides.length]); // C
console.log(slides[i++ % slides.length]); // A — wraps back!

// The negative number surprise
console.log(-7 % 3);  // -1 NOT 2
console.log(7 % -3);   // 1  NOT -1
// Rule: result takes sign of the FIRST number
Pro Tip #1 — % is not modulo
In mathematics modulo always returns a positive result. But JavaScript % is a remainder operator — the result takes the sign of the first number. -7 % 3 gives -1 in JavaScript but 2 in pure maths. To get true mathematical modulo use: ((n % m) + m) % m.
Pro Tip #2 — % for pagination
Every pagination system uses %. To know which page an item belongs to: Math.floor(itemIndex / itemsPerPage). To know position within a page: itemIndex % itemsPerPage. These two lines power every list, grid, and table in every web app.

5. The ** Exponentiation Operator — The Brain Bender 🔥

** raises a number to a power. 2 ** 8 means 2 to the power of 8 = 256. It was added in ES2017 as a cleaner alternative to Math.pow(). But it has one behavior that catches everyone off guard — it reads right to left instead of left to right.

JavaScript — ** exponentiation
// Basic use
console.log(2 ** 10);  // 1024
console.log(3 ** 3);   // 27
console.log(9 ** 0.5); // 3  (square root!)

// Old way vs new way
Math.pow(2, 8)        // 256 — old
2 ** 8               // 256 — new, cleaner

// RIGHT TO LEFT — the brain bender
console.log(2 ** 3 ** 2);
// Your brain: (2**3)**2 = 8**2 = 64
// JavaScript: 2**(3**2) = 2**9 = 512 ← right to left!

// Real world — compound interest
const principal = 1000;
const rate = 0.1;  // 10% per year
const years = 5;
const amount = principal * ((1 + rate) ** years);
console.log(amount.toFixed(2)); // 1610.51

🔥 The right-to-left rule: ** is the only JavaScript operator that evaluates right to left. Every other operator goes left to right. This makes 2 ** 3 ** 2 = 512 not 64. Always use brackets with chained ** to be explicit about your intent.

6. The Math Object — Your Extra Calculator

JavaScript has a built-in Math object with mathematical functions that go beyond basic arithmetic. These are used in almost every real project — from rounding prices to generating random numbers to calculating geometry.

JavaScript — Math object
// Rounding
Math.round(4.5)   // 5  — rounds to nearest
Math.round(4.4)   // 4
Math.floor(4.9)   // 4  — always down
Math.ceil(4.1)    // 5  — always up
Math.trunc(4.9)   // 4  — removes decimal part

// floor vs trunc — they differ on negatives!
Math.floor(-4.5)  // -5 — rounds DOWN (more negative)
Math.trunc(-4.5)  // -4 — removes decimal only

// Min and Max
Math.max(1, 5, 3, 9, 2)  // 9
Math.min(1, 5, 3, 9, 2)  // 1

// Random number between 0 and 1
Math.random()             // 0.6372... (different every time)

// Random integer between min and max — used in every game
function randInt(min, max) {
  return Math.floor(Math.random() * (max - min + 1)) + min;
}
console.log(randInt(1, 6)); // dice roll: 1 to 6

// Constants
Math.PI    // 3.141592653589793
Math.E     // 2.718281828459045
Pro Tip #1 — floor vs trunc on negatives
Math.floor(-4.5) gives -5 because floor always rounds toward negative infinity. Math.trunc(-4.5) gives -4 because trunc just removes the decimal. For positive numbers they give the same result. For negative numbers they are different. Always know which one you need.
Pro Tip #2 — Math.random() never gives exactly 1
Math.random() returns a number from 0 (inclusive) to 1 (exclusive). It can give 0 but never gives exactly 1. This is why the randInt formula uses max - min + 1 — to include the maximum value in the possible results.
Pro Tip #3 — Integer division in JavaScript
JavaScript has no integer division operator. 10 / 3 gives 3.333... not 3. Use Math.floor(10 / 3) to get 3. There is also a bitwise trick (10 / 3) | 0 which is faster but only works for numbers under 2 billion — use Math.floor() for safety.

7. Try It Yourself

Edit the code and click Run Code. Try changing the numbers and operators. Pay special attention to the results that surprised you earlier.

✏️ Try it Yourself — Arithmetic Operators
OUTPUT
// Click Run Code to see output
💡 Code edit karo aur Run dabao!

8. Practice Tasks

Task 1 — Easy: Circle Area Calculator

Calculate the area of a circle with radius 7 using the formula πr². Use Math.PI and the ** operator. Round the result to 2 decimal places using .toFixed(2). Log the result as: "Area: 153.94"

Task 2 — Medium: Temperature Converter

Write a function celsiusToFahrenheit(c) that converts Celsius to Fahrenheit using the formula: F = (C × 9/5) + 32. Test with 0°C (should give 32°F), 100°C (should give 212°F), and 37°C (body temperature — should give 98.6°F). Watch operator precedence carefully!

Task 3 — Hard: Shopping Cart with Correct Precedence

Fix the bug from the beginning of this lesson. Write a function calculateTotal(price, tax, quantity) that correctly calculates: (price + tax) × quantity. Then add a discount: if quantity is 5 or more apply 10% off using % to check if quantity is divisible by 5. Use proper brackets everywhere. Test with price=500, tax=50, quantity=5.

Next Lesson
Day 8 — Assignment Operators
Read Next Lesson →
Want daily web dev tips?
Follow Muhammad Waheed Asghar for daily JavaScript and CSS tips!