All JavaScript projects

JavaScript project

Calculator

Create a calculator for addition, subtraction, multiplication, and division with input validation.

  • Functions
  • Operators
  • Conditionals

How to run this project

  1. Create a file named index.html in a new folder.
  2. Copy the complete code below into the file and save it.
  3. Open index.html in your browser. No installation or API key is needed.

Complete project code

This single file includes the HTML interface, basic CSS styling, and JavaScript behavior. The script runs after the HTML so all the elements are available.

HTML
<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <title>Calculator</title>
  <style>
    body { font-family: system-ui, sans-serif; max-width: 640px; margin: 40px auto; padding: 0 20px; line-height: 1.6; }
    form { display: grid; gap: 12px; }
    input, select, button { font: inherit; padding: 8px; }
    button { cursor: pointer; }
    button:disabled { cursor: default; }
    li { margin: 12px 0; overflow-wrap: anywhere; }
    li button { margin-left: 12px; }
    input[type="checkbox"] { margin-right: 8px; }
    #answers { display: grid; gap: 8px; }
  </style>
</head>
<body>
<h1>Calculator</h1>
<form id="calculator-form">
  <label for="first-number">First number</label>
  <input id="first-number" type="number" step="any" required>
  <label for="operation">Operation</label>
  <select id="operation">
    <option value="add">Add (+)</option>
    <option value="subtract">Subtract (-)</option>
    <option value="multiply">Multiply (×)</option>
    <option value="divide">Divide (÷)</option>
  </select>
  <label for="second-number">Second number</label>
  <input id="second-number" type="number" step="any" required>
  <button type="submit">Calculate</button>
</form>
<p id="result" role="status">Your result will appear here.</p>
<script>
const form = document.querySelector("#calculator-form");
const firstInput = document.querySelector("#first-number");
const secondInput = document.querySelector("#second-number");
const operation = document.querySelector("#operation");
const result = document.querySelector("#result");

function calculate(first, second, operator) {
  switch (operator) {
    case "add": return first + second;
    case "subtract": return first - second;
    case "multiply": return first * second;
    case "divide":
      if (second === 0) {
        throw new Error("Cannot divide by zero.");
      }
      return first / second;
    default:
      throw new Error("Choose a valid operation.");
  }
}

form.addEventListener("submit", (event) => {
  event.preventDefault();
  const first = firstInput.valueAsNumber;
  const second = secondInput.valueAsNumber;

  if (!Number.isFinite(first) || !Number.isFinite(second)) {
    result.textContent = "Enter two valid numbers.";
    return;
  }

  try {
    const answer = calculate(first, second, operation.value);
    if (!Number.isFinite(answer)) {
      throw new Error("The result is too large. Try smaller numbers.");
    }
    result.textContent = "Result: " + answer;
  } catch (error) {
    result.textContent = error.message;
  }
});
</script>
</body>
</html>

How the code works

  1. 1. Build a form for numeric input

    The two number inputs use step="any" to accept decimals and required to reject empty values. The select element supplies an operation name. The result paragraph has role="status", allowing assistive technology to announce updates.

  2. 2. Read numbers instead of strings

    Input values are normally strings. valueAsNumber reads a numeric value directly, avoiding accidental string concatenation such as "2" + "3" producing "23". Number.isFinite rejects invalid numbers and infinite values.

  3. 3. Keep calculation in a function

    calculate takes two numbers and an operation. switch chooses the matching arithmetic operator and return sends the answer back to the caller. The function is separate from the DOM, so the calculation logic can be reused.

  4. 4. Handle invalid operations

    Dividing by zero throws an Error with a useful message. The submit listener calls calculate inside try/catch, so errors are displayed in the result paragraph. A second finite check catches numeric overflow, and textContent shows either the answer or the error.

  5. 5. Understand decimal precision

    JavaScript numbers use binary floating-point representation. Some decimal calculations, such as 0.1 + 0.2, may show a small rounding difference. As an extension, format the displayed result to a chosen number of decimal places.

Try it yourself

Calculate 12 + 3 (15), 12 - 3 (9), 12 × 3 (36), and 12 ÷ 3 (4). Then divide by 0 to see the error message and try negative numbers and decimals.

Back to all projects
Digital AI Academy

DevBrainBox Portal is proudly developed and managed by

Digital AI Academy
About the academy