Math, Numbers, and Date Objects

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.

Back to top

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 generate random numbers.

Back to top

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.

PropertyValue
EValue of Euler’s constant (E), which is about 2.71828.
LN10Value of the natural logarithm of 10, which is about 2.302585.
LN2Value of the natural logarithm of 2, which is about 0.693147.
LOG10EValue of the base 10 logarithm of E, which is about 0.43429.
LOG2EValue of the base 2 logarithm of E, which is about 1.442695.
PIValue of pi, often used with circles, which is abou 3.14159.
SQRT2Value of the square root of 2, which is about 1.4142.
SQRT1_2Value of he square root of one half, which is about 0.7071.

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

Back to top

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.

MethodPurpose
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.

Back to top

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 they 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 square 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.

Back to top

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()

Back to top

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>

Back to top

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>

Back to top

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>

Back to top

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.

Back to top

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.

Back to top

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 doen’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[0] = "This is the quote number 0.";
Quotes[1] = "This is the quote number 1.";
Quotes[2] = "This is the quote number 2.";
Quotes[3] = "This is the quote number 3.";
Quotes[4] = "This is the quote number 4.";
Quotes[5] = "This is the quote number 5.";
Quotes[6] = "This is the quote number 6.";
Quotes[7] = "This is the quote number 7.";
Quotes[8] = "This is the quote number 8.";
Quotes[9] = "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[0] = "This is the quote number 0.";
Quotes[1] = "This is the quote number 1.";
Quotes[2] = "This is the quote number 2.";
Quotes[3] = "This is the quote number 3.";
Quotes[4] = "This is the quote number 4.";
Quotes[5] = "This is the quote number 5.";
Quotes[6] = "This is the quote number 6.";
Quotes[7] = "This is the quote number 7.";
Quotes[8] = "This is the quote number 8.";
Quotes[9] = "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[0] = "http://esl.saigon.ro/img/tuyen-lam-1.jpg"; Images[1] = "http://esl.saigon.ro/img/tuyen-lam-2.jpg"; Images[2] = "http://esl.saigon.ro/img/tuyen-lam-3.jpg"; Images[3] = "http://esl.saigon.ro/img/tuyen-lam-4.jpg"; Images[4] = "http://esl.saigon.ro/img/tuyen-lam-5.jpg"; Images[5] = "http://esl.saigon.ro/img/tuyen-lam-6.jpg"; Images[6] = "http://esl.saigon.ro/img/tuyen-lam-7.jpg"; Images[7] = "http://esl.saigon.ro/img/tuyen-lam-8.jpg"; Images[8] = "http://esl.saigon.ro/img/tuyen-lam-9.jpg"; Images[9] = "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>

Back to top

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.

Back to top

The properties of Number object

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

PropertyDescription
constructorHolds the value of the constructor function that created the object.
MAX_VALUEHolds a constant number value, representing the largest value before JavaScript interprets a number as infinity.
MIN_VALUEHolds a constant number value, representing the smallest value before JavaScript interprets a number as negativ infinity.
NaNRepresents the value of “Not a number”.
NEGATIV_INFINITYRepresents the value of negative infinity.
POSITIVE_INFINITYRepresents the value of infinity.
prototypeEnables you to add properties to the objects if you wish.

Back to top

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 get with the array object which is the name of the constructor function and any public code in the function.

Back to top

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);
}

Back to top

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);
}

Back to top

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.

Back to top

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.

Back to top

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.

Back to top

The prototype property

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

Back to top

Methods of the Number object

The table below lists the methods of the number object and its purpose.

MethodPurpose
toExponential()Returns a string value that represents the number in exponential notation
toFixed()Returns a string value that represents the number rounded to the specified number of digits after the decimal.
toPrecision()Returns a string value that represents the number rounded to the specified number of significant digits.
toSource()Returns a string value that represents the source code of the object.
toString()Returns a string value for a Number object.
valueOf()User by JavaScript internally most often.

The toExponential(), toFixed(), toPrecision(), and toString() Methods

These methods return a string value which differs according to the way the Number object is formatted.

Note:
These methods can’t be used with the number itself (numeric value). Instead use them with Number objects by assigning numeric values to variables (which will make them Number objects).

var TheNumber = 5;
document.write(TheNumber.toExponential());

The output will be “5e+0”.

Back to top

The toExponential() Method

The toExponential() method returns a string.
This string is a Number object in the form of exponential notation.

var TheNumber = 5;
document.write(TheNumber.toExponential());

Back to top

The toFixed() Method

The toFixed() method returns a string. This string is a Number object rounded to the specified number of places after the decimal.

var FamilyBudget = 2000;
var FamilyMembers = 6;
var MoneyPerMember = FamilyBudget/FamilyMembers;
document.write("Each family member has $"+MoneyPerMember.toFixed(2) +" to spend");

Back to top

The toPrecision() Method

The toPrecision() method returns a string. This string is a Number object rounded to the specified number of significant digits (all digits, before and after the decimal).

var TheNumber = 12.547623;
document.write(TheNumber.toPrecision(5));

Back to top

The toString() Method

The toString() method returns the string value of a Number object or a numerical variable value. Basically you can convert 10 to “10” (a numerical value to a string value).

Back to top

The toSource() Method

The toSource() method returns a string value that represents the source code of the object. With the predefined Number object, this method returns the value of the constructor property. It is most often called by JavaScript internally and less likely to be used in code.

Back to top

The valueOf() Method

The valueOf() method it is also mainly used by JavaScript internally.

Back to top

The Date Object

The Date Object enables you to set certain time values and to get certain time values that you can use in your script. In order to use the Date Object you have to create an instance of it to which you can refer.

var new_instance = new Date();

Once you have the new instance of the Date Object you can use its properties and methods to perform various tasks.

Back to top

Properties of the Date Object

The Date Object has two properties which are presented in the table below.

PropertyPurpose
constructorHolds the value of the constructor function that created the object
prototypeEnables you to add properties to the object

Back to top

The constructor property

The constructor property holds the value of the constructor function of the object. To see what the value is you could use the code below.

var new_instance = new Date();
document.write(new_instance.constructor);

The output will be “function Date() { [native code] }” since the function code is private. This is pretty much all you can do with this property.

Back to top

The prototype property

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

Date.prototype.morning = "a.m.";
var new_instance = new Date();
document.write("This date is "+new_instance.morning);

The code above creates a new property and an instance of the Date object, and then writes on the screen the value of the new property.

Back to top

Methods of the Date Object

Although the Date object doesn’t have many properties, it does have mmany methods. The table below lists all of the Date object methods with a short description of their purpose.

MethodPurpose
getDate()Returns the day of the month based on the viewer’s local time.
getDay()Returns the numbers of days into the week based on the viewer’s local time (0-6).
getHours()Returns the numbers of hours into the day based on the viewer’s local time (0-23).
getMilliseconds()Returns the numbers of milliseconds into the second based on the viewer’s local time (0-999).
getMinutes()Returns the numbers of minutes into the hour based on the viewer’s local time (0-59).
getMonth()Returns the numbers of months into the year based on the viewer’s local time (0-11).
getSeconds()Returns the numbers of seconds into the hour based on the viewer’s local time (0-59).
getTime()Returns the number of milliseconds since 1/1/1970 for the Date Object.
getTimezoneOffset()Returns the time-zone offset (from Greenwich Meean Time) in minutes based on the viewer’s local time zone.
getYear()Returns the year based on the viewer’s local time (two digits).
getFullYear()Returns the year based on the viewer’s local time (four digits).
getUTCDate()Returns the day of the month in Coordinated Universal Time.
getUTCDay()Returns the number of days into the week in Coordinated Universal Time (0-6).
getUTCFullYear()Returns the full year in Coordinated Universal Time (four digits).
getUTCHours()Returns the number of hours into the day in Coordinated Universal Time (0-23).
getUTCMilliseconds()Returns the number of milliseconds into the current second in Coordinated Universal Time (0-999).
getUTCMinutes()Returns the number of minutes into the hours in Coordinated Universal Time (0-59).
getUTCMonth()Returns the number of months into the current year in Coordinated Universal Time(0-11).
getUTCSeconds()Returns the number of seconds into the current minute in Coordinated Universal Time (0-59).
parse()Returns the number of milliseconds since 1/1/1970 of a date sent as a parameter based on the viewer’s local time.
setDate()Sets the day of the month for an instance of the Date object.
setHours()Sets the hours for an instance of the Date object.
setMilliseconds()Sets the milliseconds for an instance of the Date object.
setMinutes()Sets the minutes for an instance of the Date object.
setMonth()Sets the month for an instance of the Date object.
setSeconds()Sets the seconds for an instance of the Date object.
setTime()Sets the time (in milliseconds since January 1, 1970, at midnight) for an instance of the Date Object.
setYear()Sets the year for an instance of the Date object (two digits).
setFullYear()Sets the year for an instance of the Date object (four digits).
setUTCDate()Sets the day of the month in Coordinated Universal Time.
setUTCFullYear()Sets the year in Coordinated Universal Time (four digits).
setUTTCHours()Sets the numbers of hours into the day in Coordinated Universal Time (0-23).
setUTCMilliseconds()Sets the number of milliseconds into the current second in Coordinated Universal Time (0-999).
setUTCMinutes()Sets the number of minutes into the hours second in Coordinated Universal Time (0-59).
setUTCMonth()Sets the number of months into the current year in Coordinated Universal Time (0-11).
setUTCSeconds()Sets the number of secods into the current minute in Coordinated Universal Time (0-59).
toDateString()Returns the date portion of the Date object as a string in American English.
toGMTString()Returns a string that is the date in Greenwich Mean Time (GMT) format (toUTCstring() is used now).
toLocaleString()Returns a string that is the date in a format based on the locale.
toLocaleDateString()Returns the date portion of the Date object as a string based on the locale.
toLocaleTimeString()Returns the time portion of the Date object as a string based on the locale.
toString()Returns a string that is the date in American English.
toTimeString()Returns the time portion of the Date object as a string in American English.

The first 19 methods in the table are methods that get values (that’s why their name starts with “get”). To use these methods you need an instance of the Date object then you can call any of the methods by using the instance name.

instanceName.method();

Note:
Of course, you need to replace “instanceName” with the actual name you want to give to your instance of the Date object and “method()” with the method function you wish to use.

Back to top

The getDate() Method

The getDate() method enables you to get the day of the month for use in script. Its returned value is a number that represents the day of the month.

Back to top

The getDay() Method

The getDay() method enables you to get the day of the week. It doesn’t return a name, it returns a number (from 0 to 6). It starts counting the days of the week from 0, which is Sunday, and it ends with 6 which is Saturday. So, if today is Wednesday then getDay() method will return 3.

Back to top

The getHours() Method

The getHours() method enables you to get the number of hours into a day (0-23). The count begins at 0 and ends at 23. If it is 4 pm the method will return 16 and at midnight it returns 0.

Back to top

The getMilliseconds() Method

The getMilliseconds() method enables you to get the number of milliseconds stored in the instance of the Date object (0-999).

Back to top

The getMinutes() Method

The getMinutes() method enables youto get the number of minutes stored in the instance of the Date object (0-59). The counts starts at 0 and it ends at 59. If it is 5:00 o’clock (either a.m. or p.m.) the method returns 0, and if it is 5:12 o’clock the method returns 12.

Back to top

The getMonth() Method

The getMonth() method enables youto get the number of months stored in the instance of the Date object (0-11). The counts starts at 0 and it endsat 11. So, for January the method will return 0, and for December it will return 11.

Back to top

The getSeconds() Method

The getSeconds() method enables youto get the number of seconds stored in the instance of the Date object (0-59). So, if the time is 1:23:29, the method returns 29; and if the time is 1:24:00, the method returns 0.

Back to top

The getTime() Method

The getTime() method gets the time (in milliseconds sinceJanuary 1, 1970 at midnight) for the instance of the Date object.

var right_now = new Date();
var the_day = right_now.getTime();
window.alert(the_day);

This assigns the result of the method to a variable so you can use it in your script.

Back to top

The getTimezoneOffset() Method

The getTimezoneOffset() method gives you the number of minutes that separate the local time from GMT. So, if you are 3 hours apart from GMT, the method will return 180 (3 X 60).

Back to top

The getYear() Method

The getYear() method returns the last two digits of the year. If the year is 1995, the method will return 95. After the year 2000 some browsers return a three digit year and others a four digit year. To avoid confusion the method getFullYear() can be used.

Back to top

The getFullYear() Method

The getFullYear() method returns a four digit year.

var this_year = new Date();
var the_year = this_year.getFullYear();
window.alert(this_year);

Back to top

The UTC Methods

The UTC methods work just like their counterparts but instead of returning information based on the user local time, it returns information based on the Universal Time.

Back to top

The Methods that set values

The methods that start with “set” are methods that set values. They are 16 methods in total. These methods allow you to set values for an instance of Date object. To do that you send them a numeric parameter based on the time and date you want to use.

var right_now = new Date();
right_now.setDate(18);
window.alert(right_now);

At this moment, it is Friday, 21 April 2017 but the output of the above script is “Tue Apr 18 2017 03:50:39 GMT+0700 (ICT)”

Back to top

The parse() Method

The parse() method returns the number of milliseconds since January 1, 1970, at midnight for a date string (such as June 16, 2017) input as a parameter.
It is usually used with setTime() method since it needs a parameter in milliseconds to set the time.

var right_now = new Date();
var milliseconds_number = Date.parse("June 16, 2017");
right_now.setTime(milliseconds_number);
window.alert(milliseconds_number);

Back to top

The toString(), toDateString(), toTimeString(), toLocaleDateString(), toLocaleTimeString() Methods

These methods return a string that represents the date and time.

var right_now = new Date();
var date_today = right_now.toString();
window.alert(date_today);

Back to top

The toGMTString() Method

The toGMTString() method returns a date string in GMT format.

var right_now = new Date();
var date_today = right_now.toGMTString();
window.alert(date_today);

Back to top

The toLocaleString() Method

The toLocaleString() method returns a date string in the format of the viewer’s locale.

var right_now = new Date();
var date_today = right_now.toLocaleString();
window.alert(date_today);

Leave a Reply