JS Calculator Code: How to Build One
The calculator for this page is switched off while it is checked. The formula is below, and the worked example in the article shows how to use it by hand.
This article explains how to write JavaScript calculator code for a basic four-function calculator (add, subtract, multiply, divide) that runs in a web browser. You will learn the core logic, how to handle user input, and how to structure the code for accuracy and future expansion. By the end, you will have a working code example and a clear understanding of the common pitfalls.
Formula
The calculator uses the standard arithmetic operators: +, -, *, and /. The formula is simply:
- Addition: result = a + b
- Subtraction: result = a – b
- Multiplication: result = a × b
- Division: result = a ÷ b (provided b ≠ 0)
Where a and b are the two numbers entered by the user, and op selects the operation. In JavaScript, these are written as a + b, a - b, a * b, and a / b.
Worked Example
Using the default values from the calculator above: a = 10, b = 5, and the operation is “Add�. The calculation is:
- Identify the operation: Add, so we use
a + b. - Substitute the values:
10 + 5. - Compute the sum:
15.
The result shown is 15.00 (to two decimal places), matching the calculator output.
Core JavaScript Logic
A basic calculator in JavaScript needs three parts: an input handler, a calculation function, and a display updater. The simplest approach is to read the two numbers from input fields, determine the selected operation, and then compute the result. Here is a minimal example:
function calculate() {
const a = parseFloat(document.getElementById('a').value);
const b = parseFloat(document.getElementById('b').value);
const op = document.getElementById('op').value;
let result;
switch (op) {
case 'add': result = a + b; break;
case 'subtract': result = a - b; break;
case 'multiply': result = a * b; break;
case 'divide': result = b !== 0 ? a / b : 'Error';
}
document.getElementById('result').textContent = result;
}
This code uses parseFloat() to convert the input strings to numbers. Without this, JavaScript would treat the inputs as text and concatenate them (e.g., “10� + “5� becomes “105�).
Handling User Input Correctly
One of the most common mistakes is forgetting to convert input values. Input fields always return strings. Use parseFloat() or Number() to convert them. Also, check for empty fields or non-numeric input. A simple validation could be:
if (isNaN(a) || isNaN(b)) {
result = 'Enter valid numbers';
}
For division, always check if the divisor is zero. In JavaScript, dividing by zero returns Infinity, which is not a useful result for a calculator. Return an error message instead.
Building a Full Calculator Interface
If you want a calculator with buttons (like a physical calculator), you need to manage a display string and a history of the last operand and operation. A common pattern is:
- When a digit button is pressed, append it to the current display.
- When an operator button is pressed, store the current value and the operator, then clear the display for the next number.
- When the equals button is pressed, compute the result using the stored value and the current value.
Here is a simplified version of the button logic:
let current = '';
let previous = null;
let operator = null;
function pressDigit(d) { current += d; updateDisplay(); }
function pressOperator(op) {
previous = parseFloat(current);
operator = op;
current = '';
}
function pressEquals() {
const b = parseFloat(current);
let result;
switch (operator) {
case '+': result = previous + b; break;
case '-': result = previous - b; break;
case '*': result = previous * b; break;
case '/': result = previous / b; break;
}
current = result.toString();
updateDisplay();
}
This approach works but does not handle chained operations (e.g., 2 + 3 + 4) correctly because it only stores one previous value. For a full-featured calculator, you would need to evaluate the expression on each operator press.
Common Mistakes and How to Avoid Them
- String concatenation instead of addition: Always convert inputs to numbers.
- Division by zero: Check for zero before dividing.
- Floating-point precision: JavaScript uses IEEE 754 floating-point, so 0.1 + 0.2 gives 0.30000000000000004. Use
toFixed()or round the result to a reasonable number of decimal places. - Not clearing the display after an operation: Users expect the display to reset after pressing an operator.
- Ignoring keyboard input: For a better user experience, add event listeners for keyboard keys.
Comparing Different Approaches
There are several ways to write a calculator in JavaScript:
- Simple function: Best for a one-off calculation on a page. Easy to read, but not reusable.
- Object-oriented: Create a Calculator class with methods. More maintainable for complex features.
- Using
eval(): You can build a string like “10+5� and evaluate it. This is very short but extremely dangerous because it can execute arbitrary code. Avoid it for security reasons. - Using a library: Libraries like math.js provide advanced math functions and expression parsing. Useful for scientific calculators, but overkill for basic ones.
For most simple calculators, the plain function or object-oriented approach is best.
Frequently Asked Questions
Why does 0.1 + 0.2 show 0.30000000000000004?
JavaScript uses binary floating-point, which cannot represent 0.1 exactly. The result is a tiny rounding error. To fix this, round the result to a set number of decimal places, e.g., result.toFixed(2).
How do I make the calculator work with keyboard input?
Add a keydown event listener to the document. Check the key pressed: digits, operators, Enter for equals, and Backspace for deleting the last character. Then call the corresponding button handler.
Is it safe to use eval() in a calculator?
No. eval() executes any JavaScript code, so a user could type something like alert('hacked') and it would run. Always parse the input manually or use a library that safely parses expressions.
How do I handle chained operations like 2 + 3 + 4?
You need to evaluate the expression when the next operator is pressed, not just when equals is pressed. Store the current result and the pending operator. When a new operator arrives, compute the previous operation and continue.
What is the best way to format the result?
Use toFixed(n) to round to n decimal places, but be aware that it returns a string. If you need a number, use parseFloat(result.toFixed(2)). For very large or very small numbers, consider using exponential notation.
Can I make a calculator that handles percentages?
Yes. Add a percentage button that divides the current value by 100. For example, if the user enters 200 and presses %, the display shows 2. Then the operation proceeds as usual. Be careful with the order of operations, as some calculators treat percentages differently.
Related
Formula used
in a | First number | - | 10 | 0 in b | Second number | - | 5 | 0 sel op | Operation | Add=1, Subtract=2, Multiply=3, Divide=4 out result | Result | - | op == 1 ? a + b : op == 2 ? a - b : op == 3 ? a * b : a / b | 2
Each line is one input (in, sel, list) or one result (out: label, unit, formula, decimals). How the calculators work
Method: the standard formula for this calculation, rounded as each result states. See how the calculators work or report an error.