Sphere volume calculator with a form in JavaScript
Intermediate · 3 min read
A box to type a number into, a button, and an answer underneath. Loan calculators, unit converters and BMI checkers all have this shape. The maths is usually the easy part. The hard part is the number itself, because what comes out of a form field is not a number at all.
In this tutorial you will build a sphere volume calculator: type a radius, press Calculate, and see the volume. Along the way you will split the job into three small pieces that are each easy to check. You should know what a function is and have seen an if statement.
The formula
The volume of a sphere with radius r is 4/3 × π × r³. In JavaScript, Math.PI is π and ** raises a number to a power, so r ** 3 is r cubed.
Form fields always give you strings
Here is the page:
<input id="radius" value="3">
<button id="go" type="button">Calculate</button>
<p id="out"></p>
An input's value is always a string, even when the box contains a number, and even on type="number". So input.value here is '3', not 3. You turn it into a number with Number(text), and you must check the result before you trust it.
Here is the exercise. Try it first if you like, or build it with me below.
10 A sphere volume calculator
fairRead a radius from a form field and show the volume of a sphere, 4/3 π r³.
Stuck? Three hints, smallest first
- 1. An input’s
valueis always a string, even ontype="number". - 2.
Number(‘’)is0, so an empty field validates as a perfectly good zero. - 3. Keep the calculation in a pure function and let the handler do only the reading and writing.
Step 1: the maths, on its own
Write the formula as a function that takes a number and returns a number. It doesn't touch the page at all.
const sphereVolume = (radius) => (4 / 3) * Math.PI * radius ** 3;
console.log(sphereVolume(3).toFixed(4)); // 113.0973
console.log(sphereVolume(4) / sphereVolume(2)); // 8
toFixed(4) rounds to four decimal places and gives back a string for display. The second line is a quick sanity check: double the radius and the volume grows eight times, because 2 × 2 × 2 is 8.
A function like this, with no page and no side effects, is called a pure function. You can check it with plain numbers.
Step 2: turn the text into a number
The obvious way is to just call Number on whatever was typed:
console.log(Number('3')); // 3
console.log(Number('abc')); // NaN
console.log(Number('')); // 0
console.log(Number(' ')); // 0
'abc' gives NaN ("not a number"), which you can catch. But look at the last two. An empty box, or a box of spaces, becomes 0, a perfectly good number. Your calculator would happily report a volume of 0 for a field nobody filled in.
So check for an empty field first, then check the number:
function parseRadius(text) {
if (typeof text !== 'string' || text.trim() === '') return { ok: false, why: 'Enter a radius.' };
const n = Number(text);
if (!Number.isFinite(n)) return { ok: false, why: `${JSON.stringify(text)} is not a number.` };
if (n <= 0) return { ok: false, why: 'The radius must be above zero.' };
return { ok: true, value: n };
}
console.log(parseRadius('2.5').value); // 2.5
console.log(parseRadius('').why); // Enter a radius.
console.log(parseRadius('abc').why); // "abc" is not a number.
console.log(parseRadius('-2').why); // The radius must be above zero.
trim() removes spaces from both ends, so ' ' becomes '' and is caught by the first check. Number.isFinite(n) is false for NaN and for infinity. A radius must also be above zero.
The function returns an object: ok: true with the value, or ok: false with a why message you can show the user.
Step 3: the handler joins them up
Now the only code that touches the page is a few lines that read, call and write:
const sphereVolume = (radius) => (4 / 3) * Math.PI * radius ** 3;
function parseRadius(text) {
if (typeof text !== 'string' || text.trim() === '') return { ok: false, why: 'Enter a radius.' };
const n = Number(text);
if (!Number.isFinite(n)) return { ok: false, why: `${JSON.stringify(text)} is not a number.` };
if (n <= 0) return { ok: false, why: 'The radius must be above zero.' };
return { ok: true, value: n };
}
const input = document.getElementById('radius');
const out = document.getElementById('out');
const button = document.getElementById('go');
button.addEventListener('click', () => {
const parsed = parseRadius(input.value);
out.textContent = parsed.ok ? `Volume = ${sphereVolume(parsed.value).toFixed(4)}` : parsed.why;
});
button.dispatchEvent(new Event('click'));
console.log(out.textContent); // Volume = 113.0973
input.value = 'abc';
button.dispatchEvent(new Event('click'));
console.log(out.textContent); // "abc" is not a number.
The ? : is the conditional operator: if parsed.ok is true, show the volume, otherwise show the reason. Setting input.value from code stands in for someone typing.
Why three pieces instead of one? Each can be checked on its own. The maths is checked with known numbers, the parsing with bad input, and only the handler deals with the page.
The full solution
The panel builds the form, clicks the button with a good radius and then with an empty box, spaces, text, a negative number and zero. Its checks confirm the volume for 3, the eight-times rule and every refusal. Press Run, then try your own values in the live demo.
allow-scripts only, so it cannot reach this page.// Pure. No DOM, so it can be checked directly.
const sphereVolume = (radius) => (4 / 3) * Math.PI * radius ** 3;
// Parsing and validating, kept apart from both the maths and the DOM.
function parseRadius(text) {
if (typeof text !== 'string' || text.trim() === '') return { ok: false, why: 'Enter a radius.' };
const n = Number(text);
if (!Number.isFinite(n)) return { ok: false, why: `${JSON.stringify(text)} is not a number.` };
if (n <= 0) return { ok: false, why: 'The radius must be above zero.' };
return { ok: true, value: n };
}
const input = el('input', { id: 'radius', value: '3' });
const out = el('p', { id: 'out' });
const button = el('button', { id: 'go' }, 'Calculate');
document.body.appendChild(el('form', {}, [input, button, out]));
button.addEventListener('click', () => {
const parsed = parseRadius(input.value);
out.textContent = parsed.ok ? `Volume = ${sphereVolume(parsed.value).toFixed(4)}` : parsed.why;
});
console.log('value is a string:', typeof input.value, JSON.stringify(input.value));
fire(button, 'click');
console.log('r=3 ->', out.textContent);
for (const bad of ['', ' ', 'abc', '-2', '0']) {
input.value = bad;
fire(button, 'click');
console.log(JSON.stringify(bad).padEnd(7), '->', out.textContent);
}
console.log("Number('') is", Number(''), '<- which is why the trim guard exists');
Output
14 checks that prove this answer
You do not have to read these. They are part of the answer panel above, so pressing
Run there executes all 14 of them and prints ok for each.
That output is the proof, and the build fails if a single check fails.
test('the volume for r=3', sphereVolume(3).toFixed(4), '113.0973');
test('for r=1 it is 4/3 pi', sphereVolume(1), (4 / 3) * Math.PI);
test('doubling the radius multiplies volume by 8', sphereVolume(4) / sphereVolume(2), 8);
test('an input value is a string, not a number', typeof input.value, 'string');
test('the handler wrote the answer into the page', (() => { input.value = '3'; fire(button, 'click'); return out.textContent; })(), 'Volume = 113.0973');
test('an empty field is refused', parseRadius('').ok, false);
test('with a message that says what to do', parseRadius('').why, 'Enter a radius.');
test('a field of spaces is refused too', parseRadius(' ').ok, false);
test('because Number("") would be 0, not NaN', Number(''), 0);
test('text is refused', parseRadius('abc').ok, false);
test('zero is refused', parseRadius('0').ok, false);
test('a negative radius is refused', parseRadius('-2').ok, false);
test('a decimal radius is accepted', parseRadius('2.5').value, 2.5);
test('and the page shows its error, not a number', (() => { input.value = 'abc'; fire(button, 'click'); return out.textContent; })(), '"abc" is not a number.');
An input's value is always a string — even type="number" hands you "3", and the assertion checks it. So every form field needs converting, and conversion needs validating.
Number('') is 0, not NaN. That single fact is why the trim() !== '' guard comes before the numeric check: without it, an empty field is a valid zero radius and your calculator confidently reports a volume of 0. A field containing only spaces does the same thing.
Splitting this into sphereVolume, parseRadius and a handler is worth the extra lines. The maths can be checked against known values, the parsing can be checked against bad input, and only the three-line handler touches the DOM at all.
Common mistakes
- Doing maths on
input.valuedirectly. It is a string.'3' + 1is'31'. Convert it withNumberfirst. - Forgetting that
Number('')is 0. An empty box looks like a valid zero. Checktext.trim() === ''before converting. - Using
4 / 3 * Math.PI * radius * 3. That multiplies by 3 instead of cubing. Writeradius ** 3.
Try it yourself
- Also show the surface area,
4 × π × r², as a second line. - Recalculate as the user types, using the input's
inputevent instead of a button. - Let the user pick centimeters or meters from a dropdown, and show the unit after the answer (
cm³orm³).