©Keren Su/CORBIS
© Keren Su/CORBIS

To perform basic arithmetic in JavaScript, such as adding numbers together, you use an assignment statement with the standard mathematical operators:

+ addition theResult=5.1+4.6
- subtraction theResult=5.1-3
/ division theResult=24/6
* multiplication theResult=7*3
The value on the right is evaluated and assigned to the left side.

A Running Total

If you wanted to keep track of a user's score for a quiz, you could implement a running total by:
  1. Defining a variable
  2. Initiating it to 0
  3. Adding 1 to it each time you need to increment it
var score=0;
score++;
score+=5;
score-=2;
score--;


The Math Object

When you need to do more complicated math than the basic operations, you can use the Math Object which has a number of methods that allow you to do operations like square roots, logarithms, trigonometry, etc:
Properties Methods
Math.abs(x)   Returns absolute value of x
Math.acos(x) Returns arc cosine of x in radians
Math.asin(x)  Returns arc sine of x in radians
Math.atan(x) Returns arc tan of x in radians
Math.atan2(y, x) Counterclockwise angle between x axis and point (x,y)
Math.ceil(x) rounds a number up
Math.cos(x) Returns the x coordinate of a point on a circle
Math.exp(x) Returns ex
Math.floor(x) rounds a number down
Math.log(x)  
Math.max(a, b) Returns the larger of two values
Math.min(a, b) Returns the smaller of two values
Math.pow(x, y) Returns Xy
Math.random() Returns a random number between 0 (inclusive) and 1 (exclusive)
Math.round(x) Rounds the number either up or down
Math.sin(x) Returns the y value of the point on a circle
Math.sqrt(x) Calculates square root.
Math.tan(x)  


Basic syntax:
theResult=Math.methodName(num1,num2,num3)

Examples:
theResult=Math.sqrt(25);	//returns 5

num1=6;
theResult=Math.pow(num1,2);	//returns 36

num1=4.46;
theResult=Math.round(num1);	//returns 4


num1=4.99;
theResult=Math.floor(num1);	//4

num1=4.2;
theResult=Math.ceil(num1);	//5

var theNumber=Math.random();	//value between 0 and 1

var theNumber=Math.floor(Math.random()*N)+1;	
    /*generates a random number that is an integer 
    from 1 to some given number N   */


Code:


<script type="text/javascript">
//<!--
function randomNumber(){
    var myFirstNum=Math.floor(Math.random()*100);  //rounds up or down to closest interger
    var mySecondNum=Math.floor(Math.random()*10);
   
    alert("my first number was "+myFirstNum +" \rmy second number was "+ 
        mySecondNum+"\rMy random number is "+myFirstNum * mySecondNum);
}	
//-->
</script>

<form id="foo" method="post" action="#">
	<p>
	    <input type="button" onclick="randomNumber();" id="doit_btn" value="pick some random numbers" />
	</p>
</form>
	

Converting Strings to Numbers

When a user inputs a number in a text box, JavaScript interprets the number as a string.
If you want to perform some mathematical operation with numbers from text boxes, you need to convert the input from strings to numbers.

The parseFloat() method takes a string value, parses it, and converts it to a floating point number.

<script type="text/javascript">
<!--
function addNums(firstEntry,secondEntry){
    length=parseFloat(firstEntry);
    width=parseFloat(secondEntry);
    document.dimensions.area.value=length*width;
}
-->
</script>


<form id="dimensions" method="post" action="">
 <p>
   <input type="text" id="num1" size="10" />
   <input type="text" id="num2" size="10" />
   <br />
   <input type="button" id="add" value="click" 
    onclick="addNums(document.dimensions.num1.value,
    document.dimensions.num2.value)" />
   <br />
   <input type="text" id="area" size="30" />
 </p>
        
</form>

Produces this:

X



You can also use parseInt(). There is a bug and the work around is to use parseInt() this way:
my_num_from_string=parseInt([text_value],10);
The 10 tells the browser that you want to use base-10 values

Returning a value from a Function

If you declare variables outside of a function, the variable is considered global (available to all functions). If you declare variables within a function, it is considered local ( only exists within that function— it goes out of scope at the end of the function). An example of a function that returns a value:
var theResult;   //global variable
theResult=calculateAverage(8,20,49);

function calculateAverage(firstNum,secondNum,thirdNum){
    var average;
    average=(firstNum+secondNum+thirdNum)/3;
    return average;
}

When the browser encounters a return in a function, it immediately exits the function and goes back to where the function was called, sending the value that follows it.
JavaScript will never get to any code within the function after the return statement.


The "with" statement

If you intend to invoke Math multiple times in your script, a good statement to remember is "with." Using it you can omit the "Math." prefix for any subsequent Math properties/methods:
 
with (Math){
    var x= sin(3.5);
    var y=tan(5);
    var result=max(x,y);
} 



JavaScript