Cylinder volume with a class in JavaScript
Beginner · 4 min read
A water tank, a tin of paint and a can of soda are all cylinders. Working out how much a cylinder holds is a common job in shopping sites, building calculators and engineering tools. It is also a good first project for learning JavaScript classes.
In this tutorial you will build a Cylinder class. You give it a radius and a height, and it tells you its volume, rounded to four decimal places. You will learn constructors, getters and the trap hidden in toFixed. You need to know what a function and an object are.
The formula
The volume of a cylinder is the area of its circle times its height: π × r² × h. In JavaScript, π is Math.PI and ** means "to the power of":
console.log(Math.PI * 4 ** 2 * 10); // 502.6548245743669
That is a tank with radius 4 and height 10.
What a class is
A class is a template for making objects of the same shape. The constructor runs once when you make a new object with new, and this is the object being made:
class Point {
constructor(x) {
this.x = x;
}
}
console.log(new Point(3).x); // 3
A class can also have methods (functions every object can call) and getters. A getter looks like a property when you read it, but it runs code each time. You write it with get in front of the name.
Here is the exercise. Try it yourself first, or read on and we will build it together.
5 Volume of a cylinder, using a class
easyBuild a cylinder class and report its volume, π r² h, to four decimal places.
Stuck? Three hints, smallest first
- 1.
toFixed(4)returns a string, not a number. - 2. Keep the exact value on the object and format only when displaying it.
- 3. A getter lets
volumebe read like a property while still being computed.
Step 1: store the radius and height
class Cylinder {
constructor(radius, height) {
this.radius = radius;
this.height = height;
}
}
const first = new Cylinder(4, 10);
console.log(first.radius, first.height); // 4 10
Each cylinder now carries its own numbers.
Step 2: add a volume getter
Add get volume() to the class. It returns the formula using the object's own values:
class Cylinder {
constructor(radius, height) {
this.radius = radius;
this.height = height;
}
get volume() {
return Math.PI * this.radius ** 2 * this.height;
}
}
const tank = new Cylinder(4, 10);
console.log(tank.volume); // 502.6548245743669
You read tank.volume with no brackets, like a property. The answer is worked out fresh on every read. Why that matters shows up in Step 5.
Step 3: round to four places
toFixed(4) rounds a number to four decimal places:
console.log(tank.volume.toFixed(4)); // 502.6548
console.log(typeof tank.volume.toFixed(4)); // string
Look at the second line. toFixed returns a string, text meant for display. Do maths with it and you get a surprise:
console.log((2.5).toFixed(1) + 1); // 2.51
The + joined two pieces of text instead of adding. So the answer keeps the exact number in volume and only formats it when showing it, in a separate method also called toFixed with a default of four places: toFixed(places = 4) { return this.volume.toFixed(places); }.
Step 4: refuse impossible sizes
A cylinder with a radius of 0 or -3 makes no sense. The constructor can refuse it by throwing an error, which stops the code and reports the problem:
function check(radius, height) {
if (radius <= 0 || height <= 0) throw new RangeError('radius and height must be positive');
return 'ok';
}
try { check(0, 5); } catch (e) { console.log(e.constructor.name); } // RangeError
RangeError is the built-in error for "this value is outside the allowed range". try...catch catches it so the program can carry on. In the answer this if line is the first line of the constructor, so a bad cylinder never gets made.
Step 5: the getter keeps up with changes
Change the radius of tank after it was made:
tank.radius = 2;
console.log(tank.volume.toFixed(4)); // 125.6637
The volume followed the change, because the getter reads this.radius every time. If the constructor had worked out the volume once and stored it, it would still say 502.6548.
The answer adds a second getter the same way, surfaceArea, which is 2 × π × r × (r + h).
The full solution
The panel has the whole class: the guard, both getters and the formatting method. It prints the exact volume, the rounded one, the surface area and the error for a zero radius, then changes the radius. Press Run to see the results.
class Cylinder {
constructor(radius, height) {
if (radius <= 0 || height <= 0) throw new RangeError('radius and height must be positive');
this.radius = radius;
this.height = height;
}
// Computed on read, so it stays correct if radius or height changes.
get volume() {
return Math.PI * this.radius ** 2 * this.height;
}
get surfaceArea() {
return 2 * Math.PI * this.radius * (this.radius + this.height);
}
// Formatting is a separate job from calculating.
toFixed(places = 4) {
return this.volume.toFixed(places);
}
}
const tank = new Cylinder(4, 10);
const refused = (() => { try { new Cylinder(0, 5); return 'no error'; } catch (e) { return e.constructor.name; } })();
console.log('radius 4, height 10');
console.log('exact volume :', tank.volume);
console.log('to 4 decimals :', tank.toFixed());
console.log('surface area :', tank.surfaceArea.toFixed(4));
console.log('negative input:', refused);
console.log('--- a getter recomputes, so changing the radius updates the volume ---');
tank.radius = 2;
console.log('radius now 2 :', tank.toFixed());
Output
11 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 11 of them and prints ok for each.
That output is the proof, and the build fails if a single check fails.
test('the volume is right to four places', new Cylinder(4, 10).toFixed(), '502.6548');
test('a smaller one', new Cylinder(2, 5).toFixed(), '62.8319');
test('toFixed returns a string, not a number', typeof new Cylinder(4, 10).toFixed(), 'string');
test('the underlying value is a number', typeof new Cylinder(4, 10).volume, 'number');
test('and it is not rounded', new Cylinder(4, 10).volume, Math.PI * 16 * 10);
test('doubling the radius quadruples the volume', new Cylinder(4, 10).volume / new Cylinder(2, 10).volume, 4);
test('doubling the height only doubles it', new Cylinder(2, 10).volume / new Cylinder(2, 5).volume, 2);
test('a zero dimension is refused', refused, 'RangeError');
test('the getter recomputes after a change', tank.toFixed(), '125.6637');
test('surface area of the changed one', tank.surfaceArea.toFixed(4), '150.7964');
test('volume is not stored as an own property', Object.hasOwn(new Cylinder(1, 1), 'volume'), false);
Two things worth keeping. toFixed returns a string — the assertion checks that, because value.toFixed(2) + 1 concatenating instead of adding is a common surprise. And using a get volume() rather than computing it once in the constructor means the value cannot go stale: the assertion after tank.radius = 2 proves the volume followed the change. A value stored in the constructor would still report the old figure.
Common mistakes
- Doing maths with the result of
toFixed. It is a string, so+joins text. Keep numbers as numbers until you display them. - Calling a getter with brackets.
tank.volume()throws a TypeError, because the value is a number, not a function. Writetank.volume. - Storing the volume in the constructor. It goes stale as soon as the radius or height changes.
Try it yourself
- Check that doubling the height doubles the volume, and doubling the radius makes it four times bigger.
- Add a
get diameter()that returns twice the radius. - Try
new Cylinder(-1, 5)inside atry...catchand print the error message.