ThisCalculator

Everyday

JavaScript Calculator Code: How to Build One

Updated · Standard formula, shown below

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.

JavaScript Calculator Code: How to Build One

To build a JavaScript calculator, you need HTML for the layout, CSS for styling, and JavaScript to handle button clicks and perform arithmetic. The core logic involves storing the current value, the previous value, and the operator, then evaluating the expression when the equals button is pressed. This article explains the essential code structure, common pitfalls, and how to extend a basic calculator into a more robust tool.

How a Basic JavaScript Calculator Works

A simple calculator typically uses a display element and a set of buttons. Each button has an event listener that calls a function when clicked. The calculator maintains a state object with the current input, the previous value, and the pending operation. When a number button is clicked, it appends the digit to the current input. When an operator is clicked, it stores the current input as the previous value, sets the operator, and clears the input for the next number. Pressing equals evaluates the stored operation and displays the result.

Here is a minimal HTML structure:

<div id="calculator">
  <input type="text" id="display" readonly>
  <button onclick="pressNumber('7')">7</button>
  <button onclick="pressOperator('+')">+</button>
  <button onclick="calculate()">=</button>
</div>

And the corresponding JavaScript:

let current = '';
let previous = '';
let operation = null;

function pressNumber(num) {
  current += num;
  document.getElementById('display').value = current;
}

function pressOperator(op) {
  if (current === '') return;
  previous = current;
  operation = op;
  current = '';
}

function calculate() {
  let result;
  const prev = parseFloat(previous);
  const curr = parseFloat(current);
  switch (operation) {
    case '+': result = prev + curr; break;
    case '-': result = prev - curr; break;
    case '*': result = prev * curr; break;
    case '/': result = curr === 0 ? 'Error' : prev / curr; break;
    default: return;
  }
  document.getElementById('display').value = result;
  current = result;
  previous = '';
  operation = null;
}

This basic version handles single operations. For a chain of operations (e.g., 2 + 3 * 4), you need to decide on operator precedence or evaluate left-to-right. Most simple calculators evaluate as you press equals, not following standard math precedence, which can surprise users expecting standard order of operations.

Handling Edge Cases and Errors

Real-world calculators must handle division by zero, multiple decimal points, and pressing operators without a number. A common approach is to disable the decimal button if the current input already contains a dot. For division by zero, display “Error” or “Infinity” and reset the state. Also, avoid using eval() because it is a security risk and can execute arbitrary code if the input is not sanitized. Instead, parse numbers with parseFloat and use a switch or if-else for operations.

Another edge case is pressing equals repeatedly. After the first equals, the result should become the first operand for the next operation. The code above already stores the result in current, so pressing an operator after equals works naturally.

Choosing the Right Approach: Basic vs. Advanced

For a simple 4-function calculator, the state-machine approach above is sufficient. If you need scientific functions (sin, cos, log, square root), you can extend the switch to include those functions, but they usually take one operand. For example, pressing “sqrt” would compute Math.sqrt(parseFloat(current)). For a calculator that follows standard operator precedence (PEMDAS), you need to implement a tokenizer and parser, such as the shunting-yard algorithm, or use a library like math.js. The choice depends on the target audience and feature set.

Common Mistakes and How to Avoid Them

  • Using eval() – It is unsafe and can break with unexpected input. Always parse and compute manually.
  • Not handling floating-point precision – JavaScript uses IEEE 754, so 0.1 + 0.2 gives 0.30000000000000004. Round the result to a reasonable number of decimal places, e.g., Math.round(result * 100) / 100.
  • Forgetting to reset the state after an error – After displaying “Error”, clear all variables so the user can start fresh.
  • Ignoring keyboard input – Add event listeners for keydown to allow typing numbers and operators, which improves usability.
  • Not handling the case where the user presses an operator after equals – The previous value should be the result, not the old first operand.

Comparing JavaScript Calculators: Vanilla vs. Frameworks

You can build a calculator with plain JavaScript, or use a framework like React, Vue, or Angular. Vanilla JS is lightweight and works in any browser without build tools. Frameworks offer better state management and component reusability, which is helpful if you plan to add complex features or maintain the code long-term. For a single-page calculator, vanilla is often simpler and faster to load. For a larger app with many UI components, a framework may reduce bugs and improve maintainability.

Safety and Security Considerations

When building a calculator for a website, never use eval() or new Function() on user input, as it can lead to cross-site scripting (XSS) attacks if the input is not properly sanitized. Always treat button clicks as the only input source, or if you allow keyboard input, validate that only digits, operators, and the decimal point are accepted. Additionally, do not trust any value from the DOM; parse and validate before using in arithmetic.

Alternatives to Building from Scratch

If you do not need to learn the internals, you can use an existing library like math.js or a pre-built widget. However, for a simple calculator, writing your own code is educational and gives full control over the UI and behavior. Another alternative is to use an online calculator generator, but that limits customization. For most educational or small projects, a custom implementation is the best balance of effort and flexibility.

Frequently Asked Questions

How do I make a calculator in JavaScript?

Create an HTML file with a display input and buttons. Attach onclick handlers to each button that call functions to update the display and store the operation. Use JavaScript variables to hold the current number, previous number, and operator, then compute the result when equals is pressed.

Why does 0.1 + 0.2 equal 0.30000000000000004?

This is due to floating-point arithmetic in JavaScript. Numbers are stored in binary, and 0.1 and 0.2 cannot be represented exactly. To fix it, round the result to a fixed number of decimal places, like Math.round(result * 100) / 100.

Is it safe to use eval() in a calculator?

No. eval() executes any string as code, which can be exploited if the input is not strictly controlled. It can also cause unexpected errors with malformed expressions. Always use a parser or a switch-based approach.

How do I add keyboard support to my calculator?

Add an event listener on the document for keydown. Check the key value: if it is a digit, decimal point, operator, or Enter/Backspace, call the corresponding function. Prevent default behavior for Enter to avoid submitting a form.

Can I build a scientific calculator with JavaScript?

Yes. Extend the operator handling to include functions like Math.sin, Math.cos, Math.log, and Math.sqrt. For functions that take one argument, apply them to the current input. For two-argument functions like power, treat them as binary operators.

How do I handle continuous calculations like 2+3+4?

In the basic approach, pressing + after 2+3 will evaluate 2+3 first, then wait for the next operand. This is typical for simple calculators. If you want to show the intermediate result, update the display after each operator press. For standard precedence, you need a more advanced parser.

Related

Formula used
in a | First number | - | 12 | 0
in b | Second number | - | 8 | 0
in op | Operation | +, -, *, / | + | 0
out result | Result | - | 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.