A short JavaScript refresher

Let's build a calculator

Six short steps from "what's a variable" to a working calculator whose math runs entirely on for loops. No prior JavaScript needed — if you know a bit of Python already, most of this will feel familiar with different punctuation.

~15 minutes · read top to bottom, run the "Try it" buttons as you go

1

Variables & numbers

A variable is a labeled box that holds a value. In JavaScript you declare one with let (a value you might change later) or const (a value that never changes).

let a = 5;        // a number, can be reassigned
const name = "Riz"; // a string, locked in
let b = 2;
a = a + 1;         // a is now 6 — this only works with let
Note — every line ends with a semicolon ;. JavaScript doesn't strictly require it, but leaving it off is a common source of bugs, so get in the habit.
2

Functions

A function is a reusable block of code that takes inputs (parameters) and hands back an output (return value). You'll write one for each of the four calculator operations.

function greet(person) {
  return "Hello, " + person;
}

greet("Riz"); // → "Hello, Riz"
Try it — calls greet("Riz")
3

The four math operators

JavaScript's built-in operators, for reference — this is what your calculator is ultimately reproducing by hand with loops in Step 5.

a + b   // add
a - b   // subtract
a * b   // multiply
a / b   // divide

Simple, right? The loop versions below are a learning exercise, not the "real" way to do math in JavaScript — but working through them is one of the best ways to get comfortable with loops.

4

The for loop

A for loop repeats a block of code a set number of times. It has three parts, separated by semicolons:

for (let i = 0; i < 3; i++) {
  console.log(i);
}
// prints: 0, 1, 2

Read it as: start — let i = 0. keep going while — i < 3. after each pass — i++ (add 1 to i). The loop body runs once per pass.

Try it — counts to 4
5

Building the four operations with loops

Here's the idea: addition is just counting up, one at a time. Multiplication is adding the same number repeatedly. A for loop is a natural fit for both.

Add

function addLoop(a, b) {
  let result = a;
  for (let i = 0; i < Math.abs(b); i++) {
    result = b >= 0 ? result + 1 : result - 1;
  }
  return result;
}

Start at a, then step up (or down, if b is negative) one unit at a time, b times.

Try it — addLoop(5, 3)

Subtract

function subtractLoop(a, b) {
  return addLoop(a, -b); // subtracting is just adding a negative
}

Multiply

function multiplyLoop(a, b) {
  let result = 0;
  let sign = b < 0 ? -1 : 1;
  for (let i = 0; i < Math.abs(b); i++) {
    result += a;
  }
  return result * sign;
}

Add a to itself, b times. That's what multiplication is.

Try it — multiplyLoop(4, 6)

Divide

function divideLoop(a, b) {
  if (b === 0) return "Cannot divide by zero";
  let sign = (a < 0) !== (b < 0) ? -1 : 1;
  let result = 0;
  for (let remainder = Math.abs(a); remainder >= Math.abs(b); remainder -= Math.abs(b)) {
    result++;
  }
  return result * sign;
}

Keep subtracting b from a until what's left is smaller than b, counting how many times you subtracted. That count is the answer.

Worth knowing — this counts whole subtractions, so it does integer division that truncates toward zero, and it always checks for b === 0 first. A real calculator would just use a / b and let JavaScript handle decimals — this version is for practicing loops, not for production.
6

Put it together

This calculator below calls the exact four functions from Step 5. Enter two whole numbers and pick an operation.

Result will show here
Show the code wiring the buttons up
function calculate(a, b, operation) {
  switch (operation) {
    case "add": return addLoop(a, b);
    case "subtract": return subtractLoop(a, b);
    case "multiply": return multiplyLoop(a, b);
    case "divide": return divideLoop(a, b);
  }
}
7

Turn the calculator into a form

A form gives the calculator a clear submit action. Label each input, listen for submit, stop the page reload, then pass the values to calculate.

Submit the form to see the answer.

Show the form event handler
calculatorForm.addEventListener("submit", (event) => {
  event.preventDefault();
  const data = new FormData(event.currentTarget);
  const answer = calculate(Number(data.get("firstNumber")), Number(data.get("secondNumber")), data.get("operation"));
});
✓

Recap

Good next step: try writing a powerLoop(base, exponent) function that raises a number to a power using a for loop, multiplying by base each pass.