Course offer · HLD · LLD · System Design at ₹799 until 30 Nov (not interview packs)

Calculator in JavaScript

Build a calculator in JavaScript using valueAsNumber and a fixed set of operation functions, not eval. Reject non-finite inputs and division by zero.

BeginnerJavaScript Mini ProjectsExample 2 of 20

Save this as index.html and open it in a browser.

calculator.js
1<!doctype html>
2<html lang="en">
3<meta charset="utf-8">
4<title>JavaScript practice</title>
5<body>
6<form id="calc"><label>First number <input id="a" type="number" step="any" required></label><select id="op" aria-label="Operation"><option>+</option><option>-</option><option>*</option><option>/</option></select><label>Second number <input id="b" type="number" step="any" required></label><button>Calculate</button></form><p id="answer"></p>
7<script>
8document.querySelector('#calc').onsubmit = event => {
9 event.preventDefault();
10 const a = document.querySelector('#a').valueAsNumber;
11 const b = document.querySelector('#b').valueAsNumber;
12 const op = document.querySelector('#op').value;
13 const output = document.querySelector('#answer');
14 if (!Number.isFinite(a) || !Number.isFinite(b)) { output.textContent = 'Enter two finite numbers.'; return; }
15 if (op === '/' && b === 0) { output.textContent = 'Cannot divide by zero.'; return; }
16 const results = { '+': () => a + b, '-': () => a - b, '*': () => a * b, '/': () => a / b };
17 const result = results[op]();
18 output.textContent = Number.isFinite(result) ? 'Result: ' + result : 'Result is too large.';
19};
20</script>
21</body>
22</html>

Sample Output

Result: 20

The numeric values 12 and 8 were added.

Cannot divide by zero.

The validation branch stops before evaluating a division with zero as divisor.

In this one

  • Read numeric form values
  • Choose an operation without eval
  • Reject division by zero
  • Check that results are finite

How it works

  1. 1

    Submit the form without a page reload.

  2. 2

    Read a and b with valueAsNumber.

  3. 3

    Reject non-finite inputs and division by zero.

  4. 4

    Choose the matching arithmetic function.

  5. 5

    Display Result: 20 for 12 + 8, or a clear error for division by zero.

Edge cases

Decimal rounding

0.1 + 0.2 can produce 0.30000000000000004.

Binary fractions cannot represent every decimal exactly. Format display values when needed, but do not pretend formatting changes the stored precision.

Very large result

Valid finite inputs can still overflow when multiplied.

Check the result with Number.isFinite before presenting it as an ordinary answer.

What's going on

This calculator reads two numbers and performs one chosen arithmetic operation. It is a useful form project because text input, number conversion, validation, and output all meet in one small page.

valueAsNumber reads each number input as a number rather than a string. That matters for addition: adding the strings "12" and "8" would produce "128", not 20. Number.isFinite rejects missing or unusable values. The operator selects one small function from the results object.

The code handles division by zero before calculating, instead of displaying Infinity as if it were a normal answer. It does not use eval, a function that executes a string as code. A fixed list of allowed operations is easier to understand and does not execute user-written expressions. Decimal arithmetic can still show small rounding differences because JavaScript numbers use binary fractions internally. Binary fractions use powers of two, so some decimal values cannot be stored exactly.

Quiz

Tap an option. The answer stays hidden until you pick.

Question 1

What would "12" + "8" produce?

Pick an answer to check it.

Question 2

Which divisor is rejected?

Pick an answer to check it.

Questions people ask

Why not use Number on an empty string?

Number("") is zero, which can hide a missing input. Number inputs with required and valueAsNumber make the intent clearer.

Can this calculate a whole expression?

No. It handles exactly two numbers and one of four operations.

Why avoid eval?

It runs text as JavaScript code. This calculator only needs four known functions, not arbitrary code execution.