This article is in need of a technical review.
Numbers
Numbers are, well, numbers, and they are implemented in JavaScript as such. All numbers are implemented in JavaScript as IEEE-754 doubles, which is a standard for defining floating-point numbers, allowing for up to 16 significant figures. This, incidentally, means that JavaScript has no integers. It also means that numbers will often behave strangely due to rounding off.
Math Object
The predefined Math
object has properties and methods for mathematical constants and functions. For example, the Math
object's PI
property has the value of pi (3.141...), which you would use in an application as
Math.PI
Similarly, standard mathematical functions are methods of Math
. These include trigonometric, logarithmic, exponential, and other functions. For example, if you want to use the trigonometric function sine, you would write
Math.sin(1.56)
Note that all trigonometric methods of Math
take arguments in radians.
The following table summarizes the Math
object's methods.
Method | Description |
---|---|
abs |
Absolute value |
sin , cos , tan |
Standard trigonometric functions; argument in radians |
acos , asin , atan , atan2 |
Inverse trigonometric functions; return values in radians |
exp , log |
Exponential and natural logarithm, base e |
ceil |
Returns least integer greater than or equal to argument |
floor |
Returns greatest integer less than or equal to argument |
min , max |
Returns lesser or greater (respectively) of two arguments |
pow |
Exponential; first argument is base, second is exponent |
random |
Returns a random number between 0 and 1. |
round |
Rounds argument to nearest integer |
sqrt |
Square root |
Unlike many other objects, you never create a Math
object of your own. You always use the predefined Math
object.
Number Object
The Number
object has properties for numerical constants, such as maximum value, not-a-number, and infinity. You cannot change the values of these properties and you use them as follows:
var biggestNum = Number.MAX_VALUE; var smallestNum = Number.MIN_VALUE; var infiniteNum = Number.POSITIVE_INFINITY; var negInfiniteNum = Number.NEGATIVE_INFINITY; var notANum = Number.NaN;
You always refer to a property of the predefined Number
object as shown above, and not as a property of a Number
object you create yourself.
The following table summarizes the Number
object's properties.
Property | Description |
---|---|
MAX_VALUE |
The largest representable number |
MIN_VALUE |
The smallest representable number |
NaN |
Special "not a number" value |
NEGATIVE_INFINITY |
Special negative infinite value; returned on overflow |
POSITIVE_INFINITY |
Special positive infinite value; returned on overflow |
The Number prototype provides methods for retrieving information from Number objects in various formats. The following table summarizes the methods of Number.prototype
.
Method | Description |
---|---|
toExponential |
Returns a string representing the number in exponential notation. |
toFixed |
Returns a string representing the number in fixed-point notation. |
toPrecision |
Returns a string representing the number to a specified precision in fixed-point notation. |
toSource |
Returns an object literal representing the specified Number object; you can use this value to create a new object. Overrides the Object.toSource method. |
toString |
Returns a string representing the specified object. Overrides the Object.toString method. |
valueOf |
Returns the primitive value of the specified object. Overrides the |
Date Object
JavaScript does not have a date data type. However, you can use the Date
object and its methods to work with dates and times in your applications. The Date
object has a large number of methods for setting, getting, and manipulating dates. It does not have any properties.
JavaScript handles dates similarly to Java. The two languages have many of the same date methods, and both languages store dates as the number of milliseconds since January 1, 1970, 00:00:00.
The Date
object range is -100,000,000 days to 100,000,000 days relative to 01 January, 1970 UTC.
To create a Date
object:
var dateObjectName = new Date([parameters]);
where dateObjectName
is the name of the Date
object being created; it can be a new object or a property of an existing object.
Calling Date
without the new
keyword simply converts the provided date to a string representation.
The parameters
in the preceding syntax can be any of the following:
- Nothing: creates today's date and time. For example,
today = new Date();
. - A string representing a date in the following form: "Month day, year hours:minutes:seconds." For example,
var Xmas95 = new Date("December 25, 1995 13:30:00")
. If you omit hours, minutes, or seconds, the value will be set to zero. - A set of integer values for year, month, and day. For example,
var Xmas95 = new Date(1995, 11, 25)
. - A set of integer values for year, month, day, hour, minute, and seconds. For example,
var Xmas95 = new Date(1995, 11, 25, 9, 30, 0);
.
JavaScript 1.2 and earlier
The Date
object behaves as follows:
- Dates prior to 1970 are not allowed.
- JavaScript depends on platform-specific date facilities and behavior; the behavior of the
Date
object varies from platform to platform.
Methods of the Date Object
The Date
object methods for handling dates and times fall into these broad categories:
- "set" methods, for setting date and time values in
Date
objects. - "get" methods, for getting date and time values from
Date
objects. - "to" methods, for returning string values from
Date
objects. - parse and UTC methods, for parsing
Date
strings.
With the "get" and "set" methods you can get and set seconds, minutes, hours, day of the month, day of the week, months, and years separately. There is a getDay
method that returns the day of the week, but no corresponding setDay
method, because the day of the week is set automatically. These methods use integers to represent these values as follows:
- Seconds and minutes: 0 to 59
- Hours: 0 to 23
- Day: 0 (Sunday) to 6 (Saturday)
- Date: 1 to 31 (day of the month)
- Months: 0 (January) to 11 (December)
- Year: years since 1900
For example, suppose you define the following date:
var Xmas95 = new Date("December 25, 1995");
Then Xmas95.getMonth()
returns 11, and Xmas95.getFullYear()
returns 1995.
The getTime
and setTime
methods are useful for comparing dates. The getTime
method returns the number of milliseconds since January 1, 1970, 00:00:00 for a Date
object.
For example, the following code displays the number of days left in the current year:
var today = new Date(); var endYear = new Date(1995, 11, 31, 23, 59, 59, 999); // Set day and month endYear.setFullYear(today.getFullYear()); // Set year to this year var msPerDay = 24 * 60 * 60 * 1000; // Number of milliseconds per day var daysLeft = (endYear.getTime() - today.getTime()) / msPerDay; var daysLeft = Math.round(daysLeft); //returns days left in the year
This example creates a Date
object named today
that contains today's date. It then creates a Date
object named endYear
and sets the year to the current year. Then, using the number of milliseconds per day, it computes the number of days between today
and endYear
, using getTime
and rounding to a whole number of days.
The parse
method is useful for assigning values from date strings to existing Date
objects. For example, the following code uses parse
and setTime
to assign a date value to the IPOdate
object:
var IPOdate = new Date(); IPOdate.setTime(Date.parse("Aug 9, 1995"));
Using the Date Object: an Example
In the following example, the function JSClock()
returns the time in the format of a digital clock.
function JSClock() { var time = new Date(); var hour = time.getHours(); var minute = time.getMinutes(); var second = time.getSeconds(); var temp = "" + ((hour > 12) ? hour - 12 : hour); if (hour == 0) temp = "12"; temp += ((minute < 10) ? ":0" : ":") + minute; temp += ((second < 10) ? ":0" : ":") + second; temp += (hour >= 12) ? " P.M." : " A.M."; return temp; }
The JSClock
function first creates a new Date
object called time
; since no arguments are given, time is created with the current date and time. Then calls to the getHours
, getMinutes
, and getSeconds
methods assign the value of the current hour, minute, and second to hour
, minute
, and second
.
The next four statements build a string value based on the time. The first statement creates a variable temp
, assigning it a value using a conditional expression; if hour
is greater than 12, (hour - 12
), otherwise simply hour, unless hour is 0, in which case it becomes 12.
The next statement appends a minute
value to temp
. If the value of minute
is less than 10, the conditional expression adds a string with a preceding zero; otherwise it adds a string with a demarcating colon. Then a statement appends a seconds value to temp
in the same way.
Finally, a conditional expression appends "P.M." to temp
if hour
is 12 or greater; otherwise, it appends "A.M." to temp
.