# Math, Numbers, and Date Objects in JavaScript

Table of content:

## The Math Object

The Math Object, as the name suggests, can be very useful when you need to perform calculations in your script.

### What is the Math Object

The Math Object is a predefined JavaScript object. Like other predefined JavaScript objects, the Math Object gives you properties and methods to work with. The Math Object is generally used for mathematical purposes.

For example if you need the value of Pi then the Math object gives you a property that gives you the value of Pi. If you need to find a square foot of a number then the Math Object enables you to do it. The Math Object can also geneerates random numbers.

### Properties of the Math Object

The properties of the Math Object hold numeric values that can be useful in mathematical calculations. They are irrational numbers so, the values listed here are nontermination, thus they are approximations.

Property Value
E Value of Euler’s constant (E), which is about 2.71828.
LN10 Value of the natural logarithm of 10, which is about 2.302585.
LN2 Value of the natural logarithm of 2, which is about 0.693147.
LOG10E Value of the base 10 logarithm of E, which is about 0.43429.
LOG2E Value of the base 2 logarithm of E, which is about 1.442695.
PI Value of pi, often used with circles, which is abou 3.14159.
SQRT2 Value of the square root of 2, which is about 1.4142.
SQRT1_2 Value of he square root of one half, which iis about 0.7071.

The properties of the Math Object contain only read only values.

### Methods of the Math Object

The methods of the Math Object allows you to perform certain calculations. The table below lists the most commonly used methods of the Math Object with a brief description of each.

Method Purpose
abs() Returns the absolute value of a number sent as parameter.
acos() Returns the arccosine of a number sent as parameter, in radians.
asin() Returns the arcsine of the number sent as parameter, in radians.
atan() Returns the arctangent of the number sent as parameter, in radians.
atan2() Returns the arctangent of the quotient of two numbers sent as parameters, in radians.
ceil() Returns the smallest integer greater than or equal to the number sent as parameter.
cos() Returns the cosine of the number sent as parameter, in radians.
exp() Returns the value of E to the power of the number sent to the method as a parameter.
floor() Returns the largest integer less than or equal to the number sent as parameter.
log() Returns the natural logarithm of the number sent as parameter.
max() Returns the larger of the two numbers that are sent as parameters.
min() Returns the smaller of the two numbers that are sent as parameters.
pow() Returns the numeric value of the first parameter raised to the power of the second parameter.
random() Returns a random number between 0 and 1; it doesn’t require a parameter.
round() Returns the value of the number sent as parameter rounded to the nearest integer.
sin() Returns the sine of the number sent as parameter, in radians.
sqrt() Returns the square root of the number sent as parameter.
tan() Returns the tangent of the number sent as parameter, in radians.

#### The basic methods of the Math Object

The basic methods are those methods that take in a single number, perform a simple calculation with it, and return a value.

The following methods are considered basic methods and the work in the same way:

abs(), acos(), asin(), atan(), cos(),
exp(), log(), sin(), sqrt(), and tan().

We are going to use sqrt() to demonstrate how methods of Math Object work by just calculating a static number.

``` document.write(Math.sqrt(4)); ```

You could also calculate the rquare root of the number input by the user.

``` <body>```

``` <form> Enter a number below <input type="text" id="UserNumber" /> </form> <button value="Calculate Square Root" id="GetSquareRoot" onclick = "RootCalculator()" >Calculate</button> <p id="TheResult"></p> <script type="text/javascript"> var a = document.getElementById("UserNumber").value; function RootCalculator () { var b = Math.sqrt(a); document.getElementById("TheResult").innerHTML = b; } </script> ```

```</body> ```

First, the number input by the user is assigned to the variable a. Then, the function RootCalculator is declared. Inside of this function the variable b is declared and it is given the value of square root of the value of variable a. The value of variable b is then written inside of the assigned paragraph when the user clicks the button “Calculate Square Root”. When this button is clicked the function is called and performs the above described tasks.

The other basic methods work in the same way; they just return different results.

#### The two parameter methods of the Math Object

The two parameter methods are the methods that take in two parameters instead of one. These methods are:

• atan2()
• max()
• min()
• pow()
##### The max() and min() methods

The max() methods takes in two numbers and returns the larger one. The min() method also takes in two numbers but it returns the smallest one.

``` <body>```

``` <form> <input type="text" id="Num1" /> <input type="text" id="Num2" /> </form> <script type="text/javascript"> function WhichOneIsBigger() { var FirstNumber = document.getElementById("Num1").value; var SecondNumber = document.getElementById("Num2").value; var BiggerNumber = Math.max(FirstNumber,SecondNumber); document.write(BiggerNumber+" is bigger"); } function WhichOneIsSmaller() { var FirstNumber = document.getElementById("Num1").value; var SecondNumber = document.getElementById("Num2").value; var SmallerNumber = Math.min(FirstNumber,SecondNumber); document.write(SmallerNumber+" is smaller"); } </script> <button type="button" id="SeeBiggerNumber" onclick="WhichOneIsBigger();" />Which number is bigger</button> <button type="button" id="SeeBiggerNumber" onclick="WhichOneIsSmaller();" />Which number is smaller</button> ```

```</body> ```

##### The pow() method

The pow() method takes in two parameters and calculates the value of the first parameter to the power of the second parameter.

``` <body>```

``` <form> Number<input type="text" id="Num1" /> To the power<input type="text" id="Num2" /> </form> <script type="text/javascript"> function WhichOneIsBigger() { var FirstNumber = document.getElementById("Num1").value; var SecondNumber = document.getElementById("Num2").value; var PowerNumber = Math.pow(FirstNumber,SecondNumber); document.write(PowerNumber); } </script> <button type="button" id="SeeBiggerNumber" onclick="WhichOneIsBigger();" />Which number is bigger</button> ```

```</body> ```

##### The ceil() method

The ceil() method stands for “ceiling” and returns the smallest integer that is greater than or equal to the number sent as the parameter.

``` <body>```

``` <form> Enter a number <input type="text" id="Num1" /> </form> <script type="text/javascript"> function TheCeilingNum() { var FirstNumber = document.getElementById("Num1").value; var CeilNumber = Math.ceil(FirstNumber); document.write("The ceiling of "+FirstNumber+" is "+CeilNumber); } </script> <button type="button" id="SeeCeilNumber" onclick="TheCeilingNum();" />Find the ceiling</button> ```

```</body> ```

##### The floor() method

The floor() method is like ceil() method but it goes the opposite way. The floor() method returns the largest integer less than or equal to the parameter sent to the method. Basically, this method just removes the decimal part of the number and leaves the integer as a result.

For example, Math.floor(15.94); will return 15 and Math.floor(15) will also return 15.

##### The round() method

The round() method works like ceil() and floor() methods but it rounds the number entered as parameter to the nearest integer whether it is greater or less than the number.

Any number having the decimal portion’s value at .5 or greater is rounded up.
Any number having the decimal portion’s value at .49 or less is rounded down.

##### The random() method

The random() method returns a random number between 0 and 1. So, you can get something like 0.2875693482 which is not very usefull.

Random integers

To get a random integer you have to make the result to have a greater range of values so you are not stuck with numbers between 0 and 1. In order to achieve this you can multiply the result of the random() method by an integer to create a larger range.

``` var RandomNumber = Math.random() * 7; document.write(RandomNumber); ```

This gives you a result between 0 and 6 but it doesn’t give you an integer yet. But if you use the floor() method it removes the decimal part of the number leaving an integer number you can easily work with.

``` var RandomNumber = Math.floor( Math.random() * 7 ); document.write(RandomNumber); ```

Basically, this gives you the floor of Math.random()*7;.

Random quotes example

This is an example of how random() method and arrays can display random quotes on your page. Instead of quotes you can have different messages or any other text that fits your situation.

First, you have to create an array with the quotes you wan to use.

``` var Quotes = new Array(10); Quotes = "This is the quote number 0."; Quotes = "This is the quote number 1."; Quotes = "This is the quote number 2."; Quotes = "This is the quote number 3."; Quotes = "This is the quote number 4."; Quotes = "This is the quote number 5."; Quotes = "This is the quote number 6."; Quotes = "This is the quote number 7."; Quotes = "This is the quote number 8."; Quotes = "This is the quote number 9."; ```

Next step, you would need a random integer between 0 and 9 (ten numbers) so we have to generate one and assign it to a variable.

``` var IntegerNumber = Math.floor(Math.random() * 10); ```

The generated random integer can be used to access the element of the array whose index number matches generated number that is now the value of the variable IntegerNumber.

``` Quotes[IntegerNumber] ```

Below is the full working example of a page that displays random quotes.

``` <body>```

``` <h1>A quote a day</h1> <p id="DisplayQuotes"></p> <script type="text/javascript"> var Quotes = new Array(10); Quotes = "This is the quote number 0."; Quotes = "This is the quote number 1."; Quotes = "This is the quote number 2."; Quotes = "This is the quote number 3."; Quotes = "This is the quote number 4."; Quotes = "This is the quote number 5."; Quotes = "This is the quote number 6."; Quotes = "This is the quote number 7."; Quotes = "This is the quote number 8."; Quotes = "This is the quote number 9."; var RandomQuote = document.getElementById("DisplayQuotes"); var IntegerNumber = Math.floor(Math.random() * 10); RandomQuote.innerHTML = Quotes[IntegerNumber]; </script> ```

```</body> ```

Here is another example that uses images instead of quotes. The images are from one of my other websites.

``` <body>```

``` <h1>An image a day</h1> <div id="ImageContainer"> </div> <script type="text/javascript"> var Images = new Array(10); Images = "http://esl.saigon.ro/img/tuyen-lam-1.jpg"; Images = "http://esl.saigon.ro/img/tuyen-lam-2.jpg"; Images = "http://esl.saigon.ro/img/tuyen-lam-3.jpg"; Images = "http://esl.saigon.ro/img/tuyen-lam-4.jpg"; Images = "http://esl.saigon.ro/img/tuyen-lam-5.jpg"; Images = "http://esl.saigon.ro/img/tuyen-lam-6.jpg"; Images = "http://esl.saigon.ro/img/tuyen-lam-7.jpg"; Images = "http://esl.saigon.ro/img/tuyen-lam-8.jpg"; Images = "http://esl.saigon.ro/img/tuyen-lam-9.jpg"; Images = "http://esl.saigon.ro/img/ao-dai-museum-saigon-1.jpg" var RandomImage = document.getElementById("ImageContainer"); var IntegerNumber = Math.floor(Math.random() * 10); RandomImage.innerHTML = '<img src="'+Images[IntegerNumber]+'" alt="A Random Image" />'; </script> ```

```</body> ```

## The Number object in JavaScript

The Number object is a predefined JavaScript object that has properties and methods and it can help you when creating scripts.

### The properties of Number object

The table below list the properties of the Number object and provides a short description of each property.

Property Description
constructor Holds the value of the constructor function that created the object.
MAX_VALUE Holds a constant number value, representing the largest value before JavaScript interprets a number as infinity.
MIN_VALUE Holds a constant number value, representing the smallest value before JavaScript interprets a number as negativ infinity.
NaN Represents the value of “Not a number”.
NEGATIV_INFINITY Represents the value of negative infinity.
POSITIVE_INFINITY Represents the value of infinity.
prototype Enables you to add properties to the objects if you wish.

#### The constructor property

The constructor property holds the value of the constructor funtion of the object. The property returns a value similar to what you gett with the array object which is the name of the constructor function and any public code in the function.

#### The MAX_VALUE property

The MAX_VALUE property is a constant number value, approximately 1.79E+308. Any number greater than this number is represented as infinity in JavaScript.

``` var HugeNumber = num1 * num2 * num3; if (HugeNumber > Number.MAX_VALUE) { window.alert("Try smaller numbers!"); } else { window.alert(HugeNumber); } ```

#### The MIN_VALUE property

The MIN_VALUE property is a constant number value, approximately 5e-324. Any number less than this number is represented as negative infinity in JavaScript.

``` var SmallNumber = num1 * num2 * num3; if (SmallNumber < Number.MIN_VALUE) { window.alert("Try larger numbers!"); } else { window.alert(SmallNumber); } ```

#### The NaN property

The NaN property is a value that represents “Not a number”. It is displayed by the browser as a string value of NaN and it is not equal to any number or any other instance of NaN.

#### The NEGATIVE_INFINITY property

The NEGATIVE_INFINITY property is a constant value that represents negative infinity. It can be used pretty much like MIN_NUMBER and MAX_NUMBER are used.

#### The POSITIVE_INFINITY property

The POSITIVE_INFINITY property is a constant value that represents positive infinity. It can be used pretty much like MIN_NUMBER and MAX_NUMBER are used.

#### The prototype property

The prototype property enables you to add a property or method to the Number object.