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
JavaScript Program to Find Area of a Circle
To find area of a circle using JavaScript, we will be using the simple formula: Area = ? × r² where r is the radius and ? is a constant value pi.
In this article, we are having radius of the circle and our task is to find the area of the circle using JavaScript.
Example Calculation
let radius = 10 and ?(pi) = 3.1415926535 Area = ? × r² Area = 3.1415926535 × 10 × 10 Area = 314.15926535
Steps to Find Area of Circle
- Store the radius of circle and pi value in variables.
- Define a function areaCircle() to calculate the area using the formula.
- The function takes pi and radius as parameters and returns the area.
- Call the function and display the result using
console.log().
Using Custom Pi Value
This example demonstrates calculating circle area with a custom pi value.
let radius = 10;
let pi = 3.141592653589793238;
function areaCircle(p, r){
return p * r * r;
}
let area = areaCircle(pi, radius);
console.log("The area of the circle is: " + area);
The area of the circle is: 314.1592653589793
Using Math.PI and Math.pow()
In this example, we use Math functions for pi value and to calculate the square of radius using Math.PI and Math.pow() respectively.
let radius = 10;
let pi = Math.PI;
function areaCircle(p, r){
return p * Math.pow(r, 2);
}
let area = areaCircle(pi, radius);
console.log("The area of the circle is: " + area);
The area of the circle is: 314.1592653589793
Simplified Approach
Here's a more concise version that directly uses Math.PI:
function calculateCircleArea(radius) {
return Math.PI * radius * radius;
}
let radius = 7.5;
let area = calculateCircleArea(radius);
console.log(`Circle with radius ${radius} has area: ${area.toFixed(2)}`);
Circle with radius 7.5 has area: 176.71
Comparison of Methods
| Method | Accuracy | Simplicity |
|---|---|---|
| Custom Pi Value | Depends on precision | Manual control |
| Math.PI | High precision | Built-in constant |
| Math.pow() | High precision | More readable for powers |
Practice and learn from a wide range of JavaScript examples, including event handling, form validation, and advanced techniques. Interactive code snippets for hands-on learning.
Conclusion
Calculating circle area in JavaScript is straightforward using the formula ? × r². Use Math.PI for better accuracy and consider toFixed() for formatting decimal places in the output.
