Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Calculate difference between circumference and area of a circle - JavaScript
In this tutorial, we'll learn how to calculate the difference between the area and circumference of a circle using JavaScript. This is a common mathematical problem that demonstrates basic geometry calculations and JavaScript functions.
Circle Formulas
Before we start coding, let's review the formulas:
Area of a circle:
? × r²
Circumference of a circle:
2 × ? × r
Where r is the radius of the circle and ? (pi) is approximately 3.14159.
JavaScript Implementation
We'll create a function that takes the radius as input and returns the absolute difference between area and circumference:
const rad = 6;
const circleDifference = radius => {
const area = Math.PI * (radius * radius);
const circumference = 2 * Math.PI * radius;
const diff = Math.abs(area - circumference);
return diff;
};
console.log(circleDifference(rad));
console.log(circleDifference(5.25));
console.log(circleDifference(1));
75.39822368615503 53.60342465187584 3.141592653589793
How It Works
The function performs these steps:
-
Calculate area:
Math.PI * (radius * radius) -
Calculate circumference:
2 * Math.PI * radius -
Find difference:
Math.abs(area - circumference)gives absolute difference - Return result: The positive difference value
Alternative Approach with Detailed Output
Here's a more detailed version that shows the individual calculations:
function detailedCircleDifference(radius) {
const area = Math.PI * Math.pow(radius, 2);
const circumference = 2 * Math.PI * radius;
const difference = Math.abs(area - circumference);
console.log(`Radius: ${radius}`);
console.log(`Area: ${area.toFixed(2)}`);
console.log(`Circumference: ${circumference.toFixed(2)}`);
console.log(`Difference: ${difference.toFixed(2)}`);
console.log('---');
return difference;
}
detailedCircleDifference(6);
detailedCircleDifference(3);
Radius: 6 Area: 113.10 Circumference: 37.70 Difference: 75.40 --- Radius: 3 Area: 28.27 Circumference: 18.85 Difference: 9.42 ---
Key Points
- Use
Math.PIfor accurate ? value in JavaScript -
Math.abs()ensures we get positive difference regardless of which value is larger - For small radii, circumference may be larger than area
- For larger radii, area typically exceeds circumference
Conclusion
This function efficiently calculates the difference between a circle's area and circumference using basic JavaScript math operations. The Math.abs() function ensures we always get a positive result, making the comparison meaningful regardless of radius size.
