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.
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;
}
}
console.log("10" + "5"); // "105"
console.log(Number("10") + Number("5")); // 15
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");
}
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;
}
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().
Author & Instructor at plus2net
I write and maintain practical tutorials on Python, PHP, SQL, JavaScript, HTML, jQuery, and web development at plus2net. The tutorials focus on clear explanations, working examples, and code that readers can test and adapt while learning.
| 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? | |