Jump to main content
Menu

Math, Number, Date, Map and Set Objects

Math Objects

  • The Math Object is unique in that it has no constructor.
  • Just specify Math (note the capitalization; you must uppercase the M), followed by a dot and the method or property that is specific to Math Objects.
  • All methods of this object are static methods.
  • By specifying Math we are initializing the object, rather than constructing and instantiating it.

Math Object Properties and Methods

Method / Property Description Code Example
abs(number) This method returns the absolute value of a number alert(Math.abs(-5));

The alert() displays 5

acos(number) This method returns the arccosine (in radians) of a number

If you pass a number outside of the -1 to 1 range, the result is NaN (Not a Number)

alert(Math.acos(0.65));

The alert() displays 0.863211890065941

asin(number) This method returns the arcsine (in radians) of a number

The numeric value returned will be between -PI/2 and PI/2 radians; a number outside that range is returned as NaN

alert(Math.asin(1));

The alert() displays 1.5707963267948966

atan(number) This method returns the arctangent of num as a numeric value between -PI/2 and PI/2 radians alert(Math.atan(1));

The alert() displays 0.7853981633974483

atan2(y,x) This method returns the angle theta of an (x,y) point as a numeric value between -PI and PI radians.

This is the counterclockwise angle between the positive x axis and the point (x,y).

Note that the y coordinate is passed before the x coordinate.

alert(Math.atan(50,75));

The alert() displays 1.550798992821746

ceil(number) This method returns the value of a number rounded upward to the nearest integer and works on both positive and negative numbers alert(Math.ceil(1.01));

The alert() displays 2

cos(number) This method returns the cosine (between -1 and 1) of the angle alert(Math.cos(0.7));

The alert() displays 0.7648421872844885

E This property returns Euler's constant alert(Math.E);

The alert() displays 2.718281828459405

exp(number) This method returns the exponential value of the number passed, using Euler's constant as the base alert(Math.exp(1));

The alert() displays 2.718281828459405


alert(Math.exp(2));

The alert() displays 7.38905609893065

floor(number) This method returns the value of a number rounded downward to the nearest integer and works on both positive and negative numbers alert(Math.floor(1.99));

The alert() displays 1

LN2 This property returns the natural logarithm of 2 alert(Math.LN2);

The alert() displays 0.6931471805599453

LN10 This property returns the natural logarithm of 10 alert(Math.LN10);

The alert() displays 2.302585092994046

log(number) This method returns the natural logarithm (base E) of a number alert(Math.log(9));

The alert() displays 2.1972245773362195

LOG2E This property returns the base-2 logarithm of E alert(Math.LOG2E);

The alert() displays 1.4426950408889634

LOG10E This property returns the base-10 logarithm of E alert(Math.LOG10E);

The alert() displays 0.4342944819032518

max(number1,number2) This method returns the number with the higher value and will accept as many numbers as you wish to pass alert(Math.max(10,-2));

The alert() displays 10

min(number1,number2) This method returns the number with the lower value and will accept as many numbers as you wish to pass alert(Math.min(10,-2));

The alert() displays -2

PI This property returns PI to a set number of places alert(Math.PI);

The alert() displays 3.141592653589793

pow(number1,number2) This method returns the value of number1 to the power of number2 alert(Math.pow(2,3));

The alert() displays 8

random() This method returns a random number between 0 and 1 alert(Math.random());
round(number) This method rounds a number to the nearest integer alert(Math.round(2.49));

The alert() displays 2


alert(Math.round(2.51));

The alert() displays 3

sin(number) This method returns the sine of a number, which is between -1 and 1 alert(Math.sin(0.9));

The alert() displays 0.7833269096274834

sqrt(number) This method returns the square root of a number alert(Math.sqrt(121));

The alert() displays 11

SQRT1_2 This property returns the square root of 1/2 alert(Math.SQRT1_2);

The alert() displays 0.7071067811865476

SQRT2 This property returns the square root of 2 alert(Math.SQRT2);

The alert() displays 1.4142135623730951

tan(number) This method returns the tangent of an angle alert(Math.tan(0.3));

The alert() displays 0.30933624960962325

Random Images Example

Reload this article or edit the random images example on CodePen and reload there to see the images change. It might take a reload or two to see a different image.

See the Pen Random Images by Jason Withrow (@jwithrow) on CodePen.

Number Object Methods

Method Description Code Example
toExponential(decimalPlaces) Converts the number object to a string object in exponential format.

The optional parameter is a number between 0 and 20 that determines the number of decimal places.

alert(Math.PI.toExponential(5));

The alert() displays 3.14159e+0

toFixed(decimalPlaces) Converts the number object to a string object in decimal format and rounds off the value.

The optional parameter is a number between 0 and 20 that determines the number of decimal places; the default is 0.

alert(Math.PI.toFixed(5));

The alert() displays 3.14159

toPrecision(decimalPlaces) Converts the number object to a string object in decimal format and rounds off the value.

The optional parameter is a number between 1 and 21 that determines the number of digits of precision (the number of significant digits). If omitted you will see numbers out to 15 decimal places.

alert(Math.PI.toPrecision(3));

The alert() displays 3.14

toString(radix) Converts the number object to a string object.

The optional parameter is a number between 2 and 36 for the radix or base. If omitted the default radix is 10. The radix is the number of unique digits, including zero.

alert(Math.PI.toString());

The alert() displays 3.141592653589793

Global Methods for Extracting a Number from a String

Method Description Code Example
parseInt(string, radix)
  • Reads from the left of the string object that is passed.
  • If the first character it finds is a number, it keeps reading until it reaches a decimal point or a non-digit character and stops there.
  • What is returned is a number object (integer) reflecting what was found.
  • If the first character encountered is not a number, then NaN is returned.
  • The second parameter (radix) is optional.
alert(parseInt('3.5 million'));

The alert() displays 3

parseFloat(string, radix)
  • Reads from the left of the string object that is passed.
  • If the first character it finds is a number, it keeps reading until it reaches a non-digit or non-decimal character and stops there.
  • What is returned is a number object (floating point) reflecting what was found.
  • If the first character encountered is not a number, then NaN is returned.
  • The second parameter (radix) is optional.
alert(parseFloat('3.5 million'));

The alert() displays 3.5

Date Objects

  • Date Objects do not have a literal, so we need to use new for instantiating a Date Object.
  • An example is:
    let theDateObj = new Date();
    

    or in object literal format:

    theDateObj : new Date(),
    
  • Dates are calculated in milliseconds since midnight 01 January, 1970 UTC (Universal Time, which is similar to but not quite the same as GMT or Greenwich Mean Time).
    • This enables operators such as -, +, <, >, ==, ===, !=, and !== to be applied when working with Date Objects and comparing them.
    • That moment in time is referred to as the Unix Epoch.

Determining the Current Date / Time

  • If no parameters are passed inside of () the object will reflect today's date and time, based on the local time of your computer. The exact formatting will vary by browser.
    let currentDate = new Date();
    alert(currentDate);
    

    The alert() outputs data such as:

    • Sat Nov 16 2024 21:24:30 GMT-0400 (Eastern Daylight Time)

Creating a Specific Date / Time

  • Passing parameters establishes a specific date, again based on midnight 01 January, 1970 UTC
  • If you decide to pass parameters, the required parameters are:
    • Year
    • Month
    • Day
  • These are passed as integers and in the sequence shown above.
  • The month ranges from 0 (January) to 11 (December).
  • The following parameters are optional and can be left out (they are automatically set to 0):
    • Hours
    • Minutes
    • Seconds
    • Milliseconds
let selectedDate = new Date(2020,8,5,14,30,15);
alert(selectedDate);

The alert() outputs data such as:

  • Sat Sep 05 2020 14:30:15 GMT-0400 (Eastern Daylight Time)

Date Object Methods

Method Description Code Example
getDate() This method returns the current day of the month (values range from 1-31) const dayOfMonth = new Date().getDate();
getDay() This method returns the current day of the week (values range from 0-6 and begin with Sunday as 0) const dayOfWeek = new Date().getDay();
getMonth() This method returns the current month (values range from 0-11) const theMonth = new Date().getMonth();
getFullYear() This method returns the current year as a four-digit number. This is preferred to the deprecated getYear() method that can return a 2- or 4-digit year, due to potential Y2K problems. const theYear = new Date().getFullYear();
getHours() This method returns the current hour (values range from 0-23) const theHour = new Date().getHours();
getMinutes() This method returns the current minute (values range from 0-59) const theMinute = new Date().getMinutes();
getSeconds() This method returns the current second (values range from 0-59) const theSecond = new Date().getSeconds();
getMilliseconds() This method returns the current millisecond (values range from 0-999) const theMillisecond = new Date().getMilliseconds();
getTime() This method returns the number of milliseconds since midnight January 1, 1970 const millisecondsToNow = new Date().getTime();
getTimezoneOffset() This method returns the difference in minutes between local time and GMT const tzOffset = new Date().getTimezoneOffset();
getUTCDate() This method returns the current day of the month according to universal time (values range from 1-31) const dayOfMonthUTC = new Date().getUTCDate();
getUTCDay() This method returns the current day of the week according to universal time (values range from 0-6) const dayOfWeekUTC = new Date().getUTCDay();
getUTCMonth() This method returns the current month according to universal time (values range from 0-11) const theMonthUTC = new Date().getUTCMonth();
getUTCFullYear() This method returns the current year (in four-digit format) according to universal time const theYearUTC = new Date().getUTCFullYear();
getUTCHours() This method returns the current hour according to universal time (values range from 0-23) const theHourUTC = new Date().getUTCHours();
getUTCMinutes() This method returns the current minute according to universal time (values range from 0-59) const theMinuteUTC = new Date().getUTCMinutes();
getUTCSeconds() This method returns the current second according to universal time (values range from 0-59) const theSecondUTC = new Date().getUTCSeconds();
getUTCMilliseconds() This method returns the current millisecond according to universal time (values range from 0-999) const theMillisecondUTC = new Date().getUTCMilliseconds();
now() This static method is always available via Date.now() (no constructor is used) and returns the number of milliseconds from midnight 01 January, 1970 until now.

All of the methods for the Math Object were static.

const currentTime = Date.now();
parse() This static method takes a date string and returns the number of milliseconds from midnight of January 1, 1970 until that date const findTime = Date.parse("September 5, 2020");
setDate() This method sets the day of the month (values range from 1-31) const theDate = new Date();
theDate.setDate(3);

This sets the date to the third day of the current month and current year.

setMonth() This method sets the month (values range from 0-11) const theDate = new Date();
theDate.setMonth(4);

This sets the date to May and uses the current day of the month and current year.

setFullYear() This method sets the year using four digits. Use this rather than the deprecated setYear() method, which accepts 2- or 4-digit values and raises potential Y2K concerns. const theDate = new Date();
theDate.setFullYear(2020);

This sets the date to 2020 with the current month and day of the month.

setHours() This method sets the hour (values range from 0-23) const theDate = new Date();
theDate.setHours(10);

This sets the hour to 10 a.m., with the minutes / seconds / milliseconds set to their current values.

setMinutes() This method sets the minutes (values range from 0-59) const theDate = new Date();
theDate.setMinutes(13);

This sets the minutes to 13 with the hours / seconds / milliseconds set to their current values.

setSeconds() This method sets the seconds (values range from 0-59) const theDate = new Date();
theDate.setSeconds(40);

This sets the seconds to 40 with the hours / minutes / milliseconds set to their current values.

setMilliseconds() This method sets the milliseconds (values range from 0-999) const theDate = new Date();
theDate.setMilliseconds(900);

This sets the milliseconds to 900 with the hours / minutes / seconds set to their current values.

setTime() Calculates a date and time by adding or subtracting a specified number of milliseconds to/from midnight January 1, 1970 UTC

A negative value will result in a date and time prior to midnight January 1, 1970 UTC

const theDate = new Date();
theDate.setTime(-97770000000);

This sets the date and time to Sat Nov 26 04:40:00 EST 1966.

setUTCDate() This method sets the day of the month according to universal time (values range from 1-31) const theDateUTC = new Date();
theDateUTC.setUTCDate(3);

This sets the date to the third day of the current month and current year.

setUTCMonth() This method sets the month according to universal time (values range from 0-11) const theMonthUTC = new Date().setUTCMonth();
setUTCFullYear() This method sets the year according to universal time (four digits) const theDateUTC = new Date();
theDateUTC.setUTCFullYear(2011);

This sets the date to 2011 with the current month and day of the month.

setUTCHours() This method sets the hour according to universal time (values range from 0-23) const theDateUTC = new Date();
theDateUTC.setUTCHours(10);

This sets the hour to 10 a.m., with the minutes / seconds / milliseconds set to their current values.

setUTCMinutes() This method sets the minutes according to universal time (values range from 0-59) const theDateUTC = new Date();
theDateUTC.setUTCMinutes(13);

This sets the minutes to 13 with the hours / seconds / milliseconds set to their current values.

setUTCSeconds() This method sets the seconds according to universal time (values range from 0-59) const theDateUTC = new Date();
theDateUTC.setUTCSeconds(40);

This sets the seconds to 40 with the hours / minutes / milliseconds set to their current values.

setUTCMilliseconds() This method sets the milliseconds according to universal time (values range from 0-999) const theDateUTC = new Date();
theDateUTC.setUTCMilliseconds(900);

This sets the milliseconds to 900 with the hours / minutes / seconds set to their current values.

toSource() This method returns an object literal representing the specified Date object. const theDate = new Date();
alert(theDate.toSource());

The alert() contains something along the lines of:

(new Date(1165194640781))
toString() This method converts a Date object to a string. This method is supported by almost all Core Objects. const theDate = new Date();
theDate.toString();
toGMTString() This method converts a Date object to a string based on GMT. The toUTCString() method has become more favored over time. const theDateGMT = new Date();
theDateGMT.toGMTString();
toUTCString() This method converts a Date object to a string based on UTC const theDateUTC = new Date();
theDateUTC.toUTCString();
toLocaleString() This method converts a Date object to a string based on local time const theDateLocal = new Date();
theDateLocal.toLocaleString();
UTC() This static method takes a date and returns the number of milliseconds since midnight January 1, 1970 based on universal time.

Consult the details about new Date() parameters when working with this method, because it functions the same way in terms of which parameters are required and which are optional.

No constructor is used because this is a static method.

const theDate = Date.UTC(2020,8,5);

Returns the number of milliseconds between midnight of January 1, 1970 and September 5, 2020 using UTC

Calendar Example

Editing this calendar example on CodePen is recommended, as you will be better able to see the code and rendering.

See the Pen Calendar by Jason Withrow (@jwithrow) on CodePen.

Map Objects

  • Map objects store key/value pairs, but they remember insertion order and accept anything as a key or a value. So you could use an Object as a key within a map, or even a function.
  • These are created via the Map() constructor and the new keyword:
    const theMap = new Map();
    
  • If you want to pass key/value pairs during map creation, you can pass an array of arrays to new Map(), with the nested arrays containing two values - the first is the key, the second is the value:
    [
      ['key1', 'value1'],
      ['key2', 'value2']
    ]
    
  • Iteration through a map can use a for-of loop; each iteration returns an array of [key, value].
  • There is also a forEach method for the map object that allows each key/value pair to be passed to a function.
  • The map has a size property, reflecting the number of key/value pairs in the map, which Object objects do not have.
  • Map objects have the benefit of not having all the extra prototype-related baggage that Object objects have; in other words, the only items in the Map are what you put there.
  • While it is possible to set properties in a Map object using dot notation or subscript notation, those properties will not be part of the map's data structure.
  • The proper approach is via the set() method:
    const theMap = new Map();
    theMap.set('someKey','someVal');
    
  • To retrieve a given key's value, use the get() method:
    const theMap = new Map();
    theMap.set('someKey','someVal');
    const theVal = theMap.get('someKey');
    
  • The other key management methods of a Map object are:
    • has(key) - Returns a boolean based on whether that key has a value in the map
    • delete(key) - Returns a boolean based on whether that key existed and was removed (so it returns false for non-existent keys)
    • clear() - Removes all key/value pairs
  • And then there are keys(), values(), and entries() methods to use within loops:
    const theMap = new Map();
    theMap.set('someKey','someVal');
    theMap.set('someKey2','someVal2');
    theMap.set('someKey3','someVal3');
    
    for (const [key, value] of theMap) {
      console.log(key + ': ' + value);
    }
    
    // console output:
    // someKey: someVal
    // someKey2: someVal2
    // someKey3: someVal3
    
    for (const key of theMap.keys()) {
      console.log(key);
    }
    
    // console output:
    // someKey
    // someKey2
    // someKey3
    
    for (const value of theMap.values()) {
      console.log(value);
    }
    
    // console output:
    // someVal
    // someVal2
    // someVal3
    
    for (const [key, value] of theMap.entries()) {
      console.log(key + ': ' + value);
    }
    
    // console output:
    // someKey: someVal
    // someKey2: someVal2
    // someKey3: someVal3
    
  • There is also a WeakMap object, which is similar in many ways to a Map object. However, there are some important differences:
    • Its keys can only be objects, so Object objects and functions are fine as keys, but primitive data types are not.
    • Its properties are not enumerable, so they will not be accessible through loops (and you cannot check its size).
    • There is no quick way to empty the WeakMap (there was a clear() method but that method is now deprecated and has essentially no support).
    • Because all the keys are objects, they can be garbage collected as soon as the reference is gone.

Set Objects

  • A Set object is a collection of unique values.
  • Strict equivalence (data type as well as value) is used when determining if a value is already in the set. Repeated attempts to add the same value will be ignored or discarded.
  • Creating a Set object involves new Set()
  • Insertion order of values is preserved.
  • The methods of Set objects are very similar to Map objects:
    • add(value) - Returns the modified Set object
    • has(value) - Returns a boolean based on whether that value is in the set
    • delete(value) - Returns a boolean based on whether the value was removed
    • clear() - Removes all values from the set
  • There is a size property, reflecting the number of items in the Set.
  • There is a forEach() method and a for-of loop can also be used.
  • There is also a WeakSet object, which has the same pros/cons as the WeakMap object.
  • Typically I leverage Set objects when I need to find distinct values in a series of options, such as speaker names for a conference. After creating the Set (which omits any duplicates), I then create an empty array, loop through the Set and copy its contents to the array, and then use the sort() method of the array object to create the final, alphabetized list of unique speakers.