Open In App

Find Volume of Cone using JavaScript

Last Updated : 13 Mar, 2024
Improve
Improve
Like Article
Like
Save
Share
Report

Mathematically, the formula for the Volume of the Cone is “volume = 1/3(pi * r * r * h)” where r is the radius of the circular base, and h is the height (the perpendicular distance from the base to the vertex). We can find this volume of cone using JavaScript by implementing various approaches along with practical implementation.

These are the following methods:

Using Math.pow and Math.PI

In this approach, we are using the formula for the volume of a cone, where we calculate it by taking 1/3 of the product of the base area (π * r^2) and the height (h), using Math.pow for exponentiation and Math.PI for the mathematical constant π. The result is then printed to the console.

Example: The below example uses Math.pow and Math.PI to find the volume of Cone in JavaScript.

Javascript
const r = 5;
const h = 10;
const vol = (1 / 3) * Math.PI * Math.pow(r, 2) * h;
console.log(vol);

Output
261.79938779914943

Using Array.map and Array.reduce() functions

In this approach, an array consists the radius and height of a cone is mapped using the map() function, squaring the radius with Math.PI if it’s the first element. Then, the reduce() function multiplies the mapped values and divides by 3 to calculate the cone volume, with the result printed to the console.

Example: The below example uses Array.map and Array.reduce() functions to find the volume of Cone in JavaScript.

Javascript
const rh = [5, 10];
const vol = rh.map((value, index) => index === 0 ?
    Math.PI * value ** 2 : value).
    reduce((acc, val) => acc * val) / 3;
console.log(vol);

Output
261.79938779914943

Using Template Literals and parseFloat() function

In this approach, a string is split into an array, and each element is converted to a floating-point number using parseFloat(). The resulting values for radius and height are then used in the cone volume formula, and the calculated volume is printed to the console.

Example: The below example uses Template Literals and parseFloat() function to find the volume of Cone in JavaScript.

Javascript
const rh = "5 10";
const [radius, height] = rh.split(" ").map(parseFloat);
const vol = (1 / 3) * Math.PI * radius ** 2 * height;
console.log(vol);

Output
261.79938779914943

Like Article
Suggest improvement
Share your thoughts in the comments

Similar Reads