Use Math.PI To Calculate Area And Circumference Of A Circle

Published on | by
Reza Baharvand
Updated on
Image for Use Math.PI To Calculate Area And Circumference Of A Circle

Introduction

The Math.PI property returns the PI π constant, approximately equal to 3.14159. For example, you can calculate the circumference and surface area of a circle using Math.PI.

console.log(Math.PI); // 3.141592653589793

Calculating Circumference Of A Circle

Write a function that accepts a number as the circle's radius as the following example:

function circleCircumference(radius) { return 2 * Math.PI * radius; } console.log(circleCircumference(16)); // 100.53096491487338

Calculating Area Of A Circle

Like the previous example, write a function to calculate the surface area:

function circleArea(radius) { return Math.PI * (radius * radius); } console.log(circleArea(16)); // 804.247719318987

You can re-write the above function by using the Math.pow() to calculate the radius^2:

function circleArea(radius) { return Math.PI * Math.pow(radius, 2); } console.log(circleArea(16)); // 804.247719318987

Also read about the Math.ceil() function and Math.floor() function.


Recent Posts

Image for Coin Flip Simulator With Javascript And CSS Animations

Coin Flip Simulator With Javascript And CSS Animations

In this tutorial, you will learn to build a small app to toss a coin using HTML, CSS, and Javascript. The possible outcomes after flipping a coin are either "Head" or "tail". The probability of getting head or tail is 50%.

Image for Check If A Function Exists Before Calling With The typeof Operator

Check If A Function Exists Before Calling With The typeof Operator

If you are sharing scripts from different modules or you have a large codebase, you can use the `typeof` operator to check if a function exists.

Image for Create A Toggle Button In Javascript To Manipulate The DOM With The toggle() Method

Create A Toggle Button In Javascript To Manipulate The DOM With The toggle() Method

The "toggle()" is a method of the "DOMTokenList". It removes something like a "class" name from the list, and returns "false". If the "class" name does not exist, it will add it to the list and return "true".

Image for Understand The Comparison Operators In Javascript And Write Logic Like A Pro

Understand The Comparison Operators In Javascript And Write Logic Like A Pro

A comparison operator compares two values with each other, and returns a logical value such as "true" or "false". The operands can be "number", "string", "logical", or "object" values.