JavaScript Program to Find Diameter if Radius is Given
Given the radius, our task is to find the diameter of the circle in JavaScript. The radius of a circle is the distance from the center of the circle to any point on its circumference denoted by r. The diameter of a circle is the distance across the circle passing through its center denoted by d.
Formula for calculating diameter is : 2r
Where, r is the radius of a circle
Below are the approaches to finding the diameter if the radius is given in JavaScript:
Table of Content
- Using Function
- Using Class
Using Function
In this approach, the code defines a function, findDiameter, that takes the radius of the Circle as an input parameter for calculating the diameter of circle. It then invokes the function with a radius value of 8. Inside the function, use the formula: 2r, to calculate the diameter of the circle. Finally, return the result.
Example: The example below shows the demonstration of finding the diameter of the circle using a function.
function findDiameter(radius) {
return 2 * radius;
}
const radius = 8;
const diameter = findDiameter(radius);
console.log("Diameter of the circle is :", diameter);
Output
Diameter of the circle is : 16
Time Complexity: O(1)
Space Complexity: O(1)
Using Class
In this approach, we define a class named Circle. Inside the class, define a constructor method that takes a parameter radius to represent the radius of the Circle. Within the constructor, calculate the diameter of the Circle using the formula: 2r.
After creating an instance of the Circle class with the desired radius passed as an argument to the constructor, call the method we created to calculate the diameter and print the result.
Example: The example below shows the demonstration of finding diameter of circle using class.
class Circle {
constructor(radius) {
this.radius = radius;
}
findDiameter() {
return 2 * this.radius;
}
}
const circle = new Circle(8);
const diameter = circle.findDiameter();
console.log("Diameter of the circle is :", diameter);
Output
Diameter of the circle is : 16
Time Complexity: O(1)
Space Complexity: O(1)