0
0
JavascriptProgramBeginner · 2 min read

JavaScript Program to Calculate Area of Circle

To calculate the area of a circle in JavaScript, use the formula area = Math.PI * radius * radius where radius is the circle's radius.
📋

Examples

Inputradius = 0
OutputArea: 0
Inputradius = 5
OutputArea: 78.53981633974483
Inputradius = 10.5
OutputArea: 346.3605900582744
🧠

How to Think About It

To find the area of a circle, you need the radius. The area is found by multiplying pi (about 3.14) by the radius squared. So, you take the radius, multiply it by itself, then multiply by pi to get the area.
📐

Algorithm

1
Get the radius value from the user or input.
2
Calculate the area by multiplying Math.PI with radius squared.
3
Return or print the calculated area.
💻

Code

javascript
const radius = 5;
const area = Math.PI * radius * radius;
console.log('Area:', area);
Output
Area: 78.53981633974483
🔍

Dry Run

Let's trace radius = 5 through the code

1

Assign radius

radius = 5

2

Calculate area

area = Math.PI * 5 * 5 = 3.141592653589793 * 25 = 78.53981633974483

3

Print area

Output: 'Area: 78.53981633974483'

radiusarea
578.53981633974483
💡

Why This Works

Step 1: Use radius as input

The radius is the distance from the center to the edge of the circle, which is needed to find the area.

Step 2: Apply area formula

The formula area = Math.PI * radius * radius calculates the space inside the circle.

Step 3: Output the result

Printing the area shows the final calculated value to the user.

🔄

Alternative Approaches

Using a function to calculate area
javascript
function calculateArea(radius) {
  return Math.PI * radius ** 2;
}
console.log('Area:', calculateArea(5));
This approach is reusable and cleaner for multiple radius values.
Using arrow function
javascript
const area = radius => Math.PI * radius * radius;
console.log('Area:', area(5));
Shorter syntax, good for quick calculations.

Complexity: O(1) time, O(1) space

Time Complexity

The calculation uses a fixed number of operations regardless of input size, so it is constant time O(1).

Space Complexity

Only a few variables are used, so space is constant O(1).

Which Approach is Fastest?

All approaches use the same formula and have constant time and space, but using a function improves code reuse and clarity.

ApproachTimeSpaceBest For
Direct calculationO(1)O(1)Simple one-time calculation
FunctionO(1)O(1)Reusability and clarity
Arrow functionO(1)O(1)Concise syntax for quick use
💡
Use Math.PI for the most accurate value of pi in JavaScript.
⚠️
Forgetting to square the radius and just multiplying by radius once.