JavaScript Calculator Demo

This calculator reads two numeric inputs and performs addition, subtraction, multiplication, or division. It converts the form values to Numbers before calculating and displays the result with textContent.

Result will appear here.

Calculator logic Top ↑

Each button supplies an operation name. The script reads the current values, validates them, then uses a switch statement to choose the calculation.

function calculate(a, b, operation) {
  switch (operation) {
    case "add": return a + b;
    case "subtract": return a - b;
    case "multiply": return a * b;
    case "divide": return b === 0 ? null : a / b;
    default: return null;
  }
}

Form values must be converted before arithmetic Top ↑

console.log("10" + "5");        // "105"
console.log(Number("10") + Number("5")); // 15

Handle division by zero explicitly Top ↑

JavaScript normally returns Infinity or -Infinity for nonzero finite numbers divided by zero. A calculator interface often gives users a clearer message instead.

if (operation === "divide" && b === 0) {
  console.log("Cannot divide by zero");
}

Complete reusable calculation function Top ↑

function calculate(rawA, rawB, operation) {
  if (rawA.trim() === "" || rawB.trim() === "") return null;
  const a = Number(rawA);
  const b = Number(rawB);
  if (!Number.isFinite(a) || !Number.isFinite(b)) return null;
  if (operation === "add") return a + b;
  if (operation === "subtract") return a - b;
  if (operation === "multiply") return a * b;
  if (operation === "divide") return b === 0 ? null : a / b;
  return null;
}

Ways to extend this calculator Top ↑

You can add percentage, exponent, square-root, rounding, keyboard controls, and calculation history. Keep each new operation separately testable rather than building expressions with eval().

JavaScript Math Reference




Subscribe to our YouTube Channel here



plus2net.com







mksharmil

23-03-2014

nice job! if input boxes are arrays in multiple rows and id's are like ="txt[]" rather than "txt"
how should we calculate then?



We use cookies to improve your browsing experience. . Learn more
HTML MySQL PHP JavaScript ASP Photoshop Articles Contact us
©2000-2026   plus2net.com   All rights reserved worldwide Privacy Policy Disclaimer