Emmanuel Akinfulubi

JavaScriptObject

Circle class with area and perimeter methods in JavaScript

Beginner · 3 min read

Circles are everywhere in code: progress rings, map radius searches, pizza-size calculators. This exercise asks for a small Circle class with two methods, one for the area and one for the perimeter (the distance around the edge, also called the circumference).

In this tutorial you will build the class, make it refuse bad input, and then use a neat check that tests both answers against each other. That check also shows you a real floating-point surprise. You need to know what a function is; classes are explained as we go.

The two formulas

For a circle with radius r:

  • area = π × r²
  • perimeter = 2 × π × r

In JavaScript, π is Math.PI, and r ** 2 means r squared.

Classes and methods

A class is a recipe for objects. The constructor runs when you write new Circle(3), and this is the new circle. A method is a function inside the class that every circle can call, like c.area().

Here is the exercise. Try it yourself first if you like, or follow the steps below.

9 Circle area and perimeter

easy

Make a circle with two methods, one for area and one for perimeter, taking the radius from the caller.

Stuck? Three hints, smallest first
  1. 1. Area is π r² and perimeter is 2 π r.
  2. 2. Validate the radius in the constructor, so a bad object cannot exist at all.
  3. 3. The ratio of area to perimeter is r / 2, which is a free way to check both at once.

Step 1: the class with two methods

Step 1

class Circle {
  constructor(radius) {
    this.radius = radius;
  }
  area() { return Math.PI * this.radius ** 2; }
  perimeter() { return 2 * Math.PI * this.radius; }
}
const c = new Circle(3);
console.log(c.area());      // 28.274333882308138
console.log(c.perimeter()); // 18.84955592153876

Both methods read this.radius, so each circle uses its own size.

Step 2: round for display

Long decimals are hard to read. toFixed(4) rounds to four places and returns text:

Step 2

console.log(c.area().toFixed(4));      // 28.2743
console.log(c.perimeter().toFixed(4)); // 18.8496

The answer puts this in a report method, so the maths and the formatting stay separate. You will see it in the next step.

Step 3: refuse a bad radius

What should new Circle(-1) or new Circle(NaN) do? A circle with a NaN radius would have a NaN area, and NaN spreads through every sum it touches. Better to refuse it in the constructor. Number.isFinite is true only for real, finite numbers:

Step 3

console.log(Number.isFinite(3));        // true
console.log(Number.isFinite(NaN));      // false
console.log(Number.isFinite(Infinity)); // false
console.log(Number.isFinite('3'));      // false

It even says false for the string '3', which is what we want: accepting '3' would invite '3km' next. Now the class, with the guard in its constructor and the report method:

JavaScript

class Circle {
  constructor(radius) {
    if (!Number.isFinite(radius) || radius <= 0) {
      throw new RangeError('radius must be a positive, finite number');
    }
    this.radius = radius;
  }
  area() { return Math.PI * this.radius ** 2; }
  perimeter() { return 2 * Math.PI * this.radius; }
  report(places = 4) {
    return `r=${this.radius} area=${this.area().toFixed(places)} perimeter=${this.perimeter().toFixed(places)}`;
  }
}
console.log(new Circle(3).report(2)); // r=3 area=28.27 perimeter=18.85

throw stops the code with an error, so a bad circle never exists.

Step 4: test the refusals

The answer wraps the constructor in a helper that reports the error's name instead of crashing:

Step 4

const bad = (value) => {
  try { new Circle(value); return 'accepted'; } catch (e) { return e.constructor.name; }
};
console.log(bad(0), bad(-1), bad(NaN), bad('3')); // RangeError RangeError RangeError RangeError
console.log(bad(3)); // accepted

Step 5: check the two answers against each other

Divide the area by the perimeter: (π r²) / (2 π r). The π cancels, one r cancels, and you are left with r / 2. That gives a free check of both methods:

Step 5

const ratio3 = new Circle(3).area() / new Circle(3).perimeter();
const ratio7 = new Circle(7).area() / new Circle(7).perimeter();
console.log(ratio3, ratio3 === 1.5); // 1.5 true
console.log(ratio7, ratio7 === 3.5); // 3.4999999999999996 false

At radius 7 the answer is a tiny bit off. The code is fine. Computers store most decimals as the nearest number they can hold, so Math.PI * 49 and 2 * Math.PI * 7 are each rounded a little, and here the two roundings don't cancel.

Step 6: compare with a tolerance

When you compare numbers that came out of calculations, ask "are they close enough?" instead of ===:

Step 6

const close = (a, b, tolerance = 1e-12) => Math.abs(a - b) < tolerance;
console.log(close(ratio7, 3.5)); // true

1e-12 means 0.000000000001. Math.abs drops the minus sign, so the order of a and b doesn't matter.

The full solution

The panel has the finished class with the guard and report, prints the area and perimeter, runs the ratio check for radius 3 and 7, and lists which inputs are rejected. Press Run to see it all.

The answer

class Circle {
  constructor(radius) {
    if (!Number.isFinite(radius) || radius <= 0) {
      throw new RangeError('radius must be a positive, finite number');
    }
    this.radius = radius;
  }

  area() { return Math.PI * this.radius ** 2; }
  perimeter() { return 2 * Math.PI * this.radius; }

  // Formatting kept apart from the maths.
  report(places = 4) {
    return `r=${this.radius} area=${this.area().toFixed(places)} perimeter=${this.perimeter().toFixed(places)}`;
  }
}

const bad = (value) => {
  try { new Circle(value); return 'accepted'; } catch (e) { return e.constructor.name; }
};

// Comparing computed floats needs a tolerance, not ===. See the note.
const close = (a, b, tolerance = 1e-12) => Math.abs(a - b) < tolerance;

const c = new Circle(3);
console.log(c.report());
console.log('area      :', c.area());
console.log('perimeter :', c.perimeter());
console.log('--- area / perimeter should be exactly r / 2 ---');
for (const r of [3, 7]) {
  const circle = new Circle(r);
  const ratio = circle.area() / circle.perimeter();
  console.log(`r=${r}  ratio=${ratio}  r/2=${r / 2}  exactly equal? ${ratio === r / 2}`);
}
console.log('<- true for r=3, false for r=7, and the maths is identical');
console.log('--- rejected inputs ---');
for (const v of [0, -1, NaN, Infinity, '3']) console.log(String(v).padEnd(10), bad(v));

Output


      
17 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 17 of them and prints ok for each. That output is the proof, and the build fails if a single check fails.

17 checks

test('area of radius 3, to four places', c.area().toFixed(4), '28.2743');
test('perimeter of radius 3', c.perimeter().toFixed(4), '18.8496');
test('radius 1 has area pi', new Circle(1).area(), Math.PI);
test('and perimeter 2 pi', new Circle(1).perimeter(), 2 * Math.PI);
test('area over perimeter is r/2', close(c.area() / c.perimeter(), c.radius / 2), true);
test('and for a different radius too', close(new Circle(7).area() / new Circle(7).perimeter(), 3.5), true);
test('but at r=7 it is not EXACTLY 3.5', new Circle(7).area() / new Circle(7).perimeter() === 3.5, false);
test('it is off by a fraction too small to matter', new Circle(7).area() / new Circle(7).perimeter(), 3.4999999999999996);
test('while at r=3 the same maths lands exactly', new Circle(3).area() / new Circle(3).perimeter() === 1.5, true);
test('doubling the radius quadruples the area', new Circle(6).area() / new Circle(3).area(), 4);
test('but only doubles the perimeter', new Circle(6).perimeter() / new Circle(3).perimeter(), 2);
test('a zero radius is refused', bad(0), 'RangeError');
test('a negative radius is refused', bad(-1), 'RangeError');
test('NaN is refused', bad(NaN), 'RangeError');
test('Infinity is refused', bad(Infinity), 'RangeError');
test('a numeric string is refused too', bad('3'), 'RangeError');
test('the report reads correctly', c.report(2), 'r=3 area=28.27 perimeter=18.85');

The constructor guard uses Number.isFinite rather than typeof === 'number', so NaN and Infinity are rejected. Both would otherwise produce a circle whose area is NaN, and NaN spreads silently through every later calculation. Refusing the string '3' is deliberate too: accepting it would mean new Circle('3') works while new Circle('3km') quietly produces NaN.

area / perimeter should be exactly r / 2, and it is a good check because it relates the two answers to each other without restating either formula. It is also where this exercise bites. At r = 3 the ratio is exactly 1.5. At r = 7 the identical arithmetic gives 3.4999999999999996, and the assertions above pin down both results.

Nothing is wrong with the code. π × 49 and 2 × π × 7 each round to the nearest representable double, and the two roundings do not cancel. This is why computed floating-point values are compared with a tolerance — Math.abs(a - b) < 1e-12 — and not with ===. The one place to avoid the problem entirely is money: count in kobo, as integers.

Common mistakes

  • Checking typeof radius === 'number'. NaN and Infinity are numbers too, so they slip through. Use Number.isFinite.
  • Comparing calculated decimals with ===. Tiny rounding differences make it false. Compare with a tolerance.
  • Doing maths on the toFixed result. It is a string. Round only for display.

Try it yourself

  1. Add a diameter() method and check that perimeter() / diameter() is close to Math.PI.
  2. Show that doubling the radius makes the area four times bigger but the perimeter only twice as big.
  3. Find another whole-number radius from 1 to 20 where area / perimeter === r / 2 is false.

Keep practising

Newsletter

New writing, when it lands.

Occasional notes on shipping software with AI agents. No schedule, no filler, unsubscribe in one click.