We continue on our journey through JavaScript built-in objects by offering a quick overview of the **Math object**.

You already had occasion to taste the power of the Math object back in lesson 7, where you used its **random() method** to generate a random number between 0 and 1, and its **floor() method** to round down the resulting random number.

The **Math object** allows you to write scripts that perform complex mathematical tasks in the blink of an eye.

In this lesson you will use:

**Math.PI**to calculate the circumference of a circle;**Math.sqrt()**to calculate a square root value.

In the process, you will learn how to use:

**parseInt()/parseFloat()**to convert strings to numbers;**isNaN()**to check whether a value is or is not a number;

## Math.PI

This property stores the value of PI, a mathematical constant that amounts to approximately 3.14159.

Let’s quickly refresh our school math. Here are some definitions:

### Circle

A circle is a shape with all points the same distance from the center:

- the round border surrounding the shape (the color blue in the graphic above), is the circle
**circumference**; - the line cutting the circle horizontally in half (the color red in the graphic above) is the circle
**diameter**; - each half of the diameter represents a
**radius**.

PI is the **ratio of the circumference of a circle to the diameter**.

If you need this value in your JavaScript program, use **Math.PI**. Just try this one out between enclosing <script> tags of an HTML page:

//store and display the value of PI: var pi = Math.PI; document.write(pi);

## Try out: use Math.PI to find out the circumference of a circle

It’s time for this lesson’s first *try out exercise*. We’re going to build a simple application where the user enters a number representing the radius of a circle, clicks a button, and the program calculates the circumference and displays it on the page.

Keeping in mind that the radius is half the diameter, and that the formula to calculate the circumference is **PI * diameter**, our JavaScript statement to calculate the circumference given the radius will be: **2 * (Math.PI * radius)**.

First things first: prepare an HTML document like this one:

<!DOCTYPE html> <html> <head> <title>Lesson 12: JavaScript Objects - Math Object</title><script type="text/javascript" src="lesson12_tryout1.js"></script></head> <body> <h1>Lesson 12: Circumference calculator</h1> <p>Enter length of radius: <input type="text" id="txtRadius" /></p> <p><input type="button" id="btnSubmit" value="Calculate circumference" /></p> <p id="result"></p> </body> </html>

The HTML page above references an external JavaScript file, *lesson12_tryout1.js*, and contains an inputbox, a button, and a paragraph where the result of the calculation will be displayed. Make sure these 3 crucial elements have an **id value** so your JavaScript script will have an easy to reach hook on those elements.

Now create a JavaScript document and name it *lesson12_tryout1.js*. This file will contain 3 functions:

**init()**initializes the script by binding the*processAnswer() function*to its appropriate event, that is,**the btnSubmit onclick event**;**processAnswer()**checks the answer submitted by the user, calls the function that performs the calculation, and displays the result;**getCircumference(rad)**gets passed the radius value as argument, performs the actual calculation, and returns the circumference.

//init() function binds the processAnswer() function //to the onclick event of the button function init() { var myButton = document.getElementById("btnSubmit"); myButton.onclick = processAnswer; } /*********************************************/ //Bind the init function to the onload event onload = init; /*********************************************/ //This function checks the user's input, //calls the function that performs the calculation, //and displays the result function processAnswer() { //store a reference to the inputbox var inputBox = document.getElementById("txtRadius"); //get the radius value entered in the inputbox //make sure to convert the string (text) to a number: //calculations can only be performed with numbers, //and the value in the inputbox is processed as string. //parseInt(string)andparseFloat(string)//take a string as input and return an integer //or a floating point number respectively. var radius =parseInt(inputBox.value); //get a reference to the paragraph to display result var result = document.getElementById("result"); //create and initialize a var to store the result var resultString = ""; //Perform some validation on the user's input: //if the value entered by the user is not a number //alert the user.isNaN(value)takes //a value as input andreturns true if the value is not a number,//itreturns false if the value is a number.//the expression below is short for: //if (isNaN(radius) == true) if(isNaN(radius)){ alert("Please, enter a number"); } else { //if the user has correctly entered a number, //call the function that performs the calculation //and display the result on the page var circ = getCircumference(radius); resultString = "Circumference is: " + circ; result.innerHTML = resultString; } } /*********************************************/ //This is the function that performs the calculation: //it takes the radius as input and returns the circumference function getCircumference(rad) { var circumference =2 * (Math.PI * rad); return circumference; }

Save all your files and run the HTML page in the browser. You should see something like the page indicated by following the example link above.

If you click the button without entering any value in the inputbox, or if you enter a letter rather than a number, the program asks you to enter a number value.

As you click the button, the calculation is performed and the result is displayed on the page.

## Math.sqrt()

**Math.sqrt(number)** takes a **number as argument and returns the square root of that number**.

If a negative number is entered as argument, for instance **Math.sqrt(-5)**, the function returns **NaN**, that is, a value that JavaScript does not treat as a number.

Brushing up on our school math, the square root of 25, for example, is that number that multiplied by itself yields 25 as a result, that is, 5.

The formula is: **square of n = n * n**. JavaScript performs this calculation automatically. Here’s a quick demo: type the following code between enclosing <script> tags of an HTML page:

var squareRoot = Math.sqrt(25); document.write("The square root of 25 is: " + squareRoot); //This should print: //The square root of 25 is: 5

## Try out: square root calculator

You will build a simple square root calculator. Here are the requirements for this little application:

- the user will be able to enter a number value into an inputbox;
- the user will be able to click a button that calculates the square root of the number entered into the inputbox;
- the result will be displayed on the web page.

Create a fresh HTML page with an inputbox, 1 button, and a paragraph where the result will be displayed. These HTML elements contain **id attributes** that will provide a handy hook for our JavaScript code.

<!DOCTYPE html> <html> <head> <title>Lesson 12: JavaScript Objects - Math Object</title><script type="text/javascript" src="lesson12_tryout2.js"></script></head> <body> <h1>Lesson 12: Square root calculator</h1> <p>Enter a number: <input type="text" id="txtNumber" /></p> <p><input type="button" id="btnSubmit" value="Calculate square root" /></p> <p id="result"></p> </body> </html>

Now create the *lesson12_tryout2.js* file. This file will contain 3 functions:

**init()**initializes the script by binding the*displaySquare() function*to its appropriate event, that is,**the btnSubmit onclick event**;**displaySquare()**checks the answer submitted by the user, calls the function that performs the calculation, and displays the result;**calculateSquare(input)**gets passed the number value entered by the user as argument, performs the actual calculation, and returns the the square root.

//write the function to initialize the script function init() { //Bind function that processes the result to //the onclick event of the button var myButton = document.getElementById("btnSubmit"); myButton.onclick = displaySquare; } /**************************************************/ //Bind the init() function to the onload event onload = init; /**************************************************/ //Here we call the function that performs //the square root calculation, then we format and //display the result functiondisplaySquare(){ //we store the value from the inputbox into a var. //Notice how we concatenate several methods//in one statement (be careful with those brackets). //If you find it a bit confusing, store a reference to the inputbox //in its own var and then use it to extract its value property //and finally pass it as argument of parseInt(), like so: //var inputBox = document.getElementById("txtNumber"); //var inputVal = parseInt(inputBox.value); var inputVal = parseInt(document.getElementById("txtNumber").value); //we store a reference to the paragraph //where the result will be displayed var result = document.getElementById("result"); //we create the var that stores the result message var resultMessage = ""; //we ensure the input value is a number: //if the user did not enter a number, we send an alert if (isNaN(inputVal)) { alert("Please, enter a number"); } else { //If the input is in correct format, we call //the function that performs the calculation var squareVal = calculateSquare(inputVal); //this is a nested if statement: it's inside another //if statement to perform further checks: //if squareVal stores a value (if the calculation was successful) - //- this isshort for: if (squareVal == true)if (squareVal) { //we build this message to the user: resultMessage = "Square root of " + inputVal + " is " + squareVal; } //else, that is, if the calculation was not successful else { //we build a different message to the user: resultMessage = "Sorry, an error occurred"; } } //finally, we display the message using innerHTML result.innerHTML = resultMessage; } /**************************************************/ //This function calculates the square root: //it takes in the number entered by the user //and returns the result of the calculation function calculateSquare(input) { var squareVal = Math.sqrt(input); return squareVal; }

Save all files and preview your work in a browser. You should see something similar to the example indicated by following the link above.

Enter a number into the inputbox and click the button. If you enter anything but a number into the inputbox (or if you leave the inputbox empty), you’ll be alerted by a popup box asking you to enter a number. If all goes well, the square root of the number you enter in the inputbox will be displayed on the page.

If the application is not working, check your typing, especially letter casing, brackets, and semi-colons ( ; ). If you have any doubts, just drop us a line in the forum dedicated to this tutorial.

## Summary

You’ve made it to the bottom of the page, congratulations! After this lesson you’ve added new tools to your JavaScript toolbox: the **PI property and sqrt() method of the Math object**. You also know how to convert a string (text) to a number data type with **parseInt() and parseFloat()**, so that you can use the value to perform calculations. Finally, you learned how to check user input with **isNaN()**.

It’s time for your break before the next big topic: the **Array object**.