Built-in Objects - Object-Oriented JavaScript Second Edition (2013)

Object-Oriented JavaScript Second Edition (2013)

Appendix C. Built-in Objects

This Appendix lists the built-in constructor functions outlined in the ECMAScript (ES) standard, together with the properties and methods of the objects created by these constructors. ES5-specific APIs are listed separately.

Object

Object() is a constructor that creates objects, for example:

> var o = new Object();

This is the same as using the object literal:

> var o = {}; // recommended

You can pass anything to the constructor and it will try to guess what it is and use a more appropriate constructor. For example, passing a string to new Object() will be the same as using the new String() constructor. This is not a recommended practice (it's better to be explicit than let guesses creep in), but still possible.

> var o = new Object('something');

> o.constructor;

function String() { [native code] }

> var o = new Object(123);

> o.constructor;

function Number() { [native code] }

All other objects, built-in or custom, inherit from Object. So, the properties and methods listed in the following sections apply to all types of objects.

Members of the Object constructor

Have a look at the following table:

Property/method

Description

Object.prototype

The prototype of all objects (also an object itself). Anything you add to this prototype will be inherited by all other objects, so be careful.

> var s = new String('noodles');

> Object.prototype.custom = 1;

1

> s.custom;

1

The Object.prototype members

Have a look at the following table:

Property/method

Description

constructor

Points back to the constructor function used to create the object, in this case, Object.

> Object.prototype.constructor === Object;

true

> var o = new Object();

> o.constructor === Object;

true

toString(radix)

Returns a string representation of the object. If the object happens to be a Number object, the radix parameter defines the base of the returned number. The default radix is 10.

> var o = {prop: 1};

> o.toString();

"[object Object]"

> var n = new Number(255);

> n.toString();

"255"

> n.toString(16);

"ff"

toLocaleString()

The same as toString(), but matching the current locale. Meant to be customized by objects, such as Date(), Number(), and Array() and provide locale-specific values, such as different date formatting. In the case of Object() instances as with most other cases, it just calls toString().

In browsers, you can figure out the language using the property language (or userLanguage in IE) of the navigator BOM object:

> navigator.language;

"en-US

"

valueOf()

Returns a primitive representation of this, if applicable. For example, Number objects return a primitive number and Date objects return a timestamp. If no suitable primitive makes sense, it simply returns this.

> var o = {};

> typeof o.valueOf();

"object"

> o.valueOf() === o;

true

> var n = new Number(101);

> typeof n.valueOf();

"number"

> n.valueOf() === n;

false

> var d = new Date();

> typeof d.valueOf();

"number"

> d.valueOf();

1357840170137

hasOwnProperty(prop)

Returns true if a property is an own property of the object, or false if it was inherited from the prototype chain. Also returns false if the property doesn't exist.

> var o = {prop: 1};

> o.hasOwnProperty('prop');

true

> o.hasOwnProperty('toString');

false

> o.hasOwnProperty('fromString');

false

isPrototypeOf(obj)

Returns true if an object is used as a prototype of another object. Any object from the prototype chain can be tested, not only the direct creator.

> var s = new String('');

> Object.prototype.isPrototypeOf(s);

true

> String.prototype.isPrototypeOf(s);

true

> Array.prototype.isPrototypeOf(s);

false

propertyIsEnumerable(prop)

Returns true if a property shows up in a for-in loop.

> var a = [1, 2, 3];

> a.propertyIsEnumerable('length');

false

> a.propertyIsEnumerable(0);

true

ECMAScript 5 additions to Object

In ECMAScript 3 all object properties can be changed, added, or deleted at any time, except for a few built-in properties (for example, Math.PI). In ES5 you have the ability to define properties that cannot be changed or deleted—a privilege previously reserved for built-ins. ES5 introduces the concept of property descriptors that give you tighter control over the properties you define.

Think of a property descriptor as an object that specifies the features of a property. The syntax to describe these features is a regular object literal, so property descriptors have properties and methods of their own, but let's call them attributes to avoid confusion. The attributes are:

· value – what you get when you access the property

· writable – can you change this property

· enumerable – should it appear in for-in loops

· configurable – can you delete it

· set() – a function called any time you update the value

· get() – called when you access the value of the property

Further, there's a distinction between data descriptors (you define the properties enumerable, configurable, value, and writable) and accessor descriptors (you define enumerable, configurable, set(), and get()). If you define set() or get(), the descriptor is considered an accessor and attempting to define value or writable will raise an error.

Defining a regular old school ES3-style property:

var person = {};

person.legs = 2;

The same using an ES5 data descriptor:

var person = {};

Object.defineProperty(person, "legs", {

value: 2,

writable: true,

configurable: true,

enumerable: true

});

The value of value if set to undefined by default, all others are false. So, you need to set them to true explicitly if you want to be able to change this property later.

Or, the same property using an ES5 accessor descriptor:

var person = {};

Object.defineProperty(person, "legs", {

set: function (v) {this.value = v;},

get: function (v) {return this.value;},

configurable: true,

enumerable: true

});

person.legs = 2;

As you can see property descriptors are a lot more code, so you only use them if you really want to prevent someone from mangling your property, and also you forget about backwards compatibility with ES3 browsers because, unlike additions to Array.prototype for example, you cannot "shim" this feature in old browsers.

And the power of the descriptors in action (defining a nonmalleable property):

> var person = {};

> Object.defineProperty(person, 'heads', {value: 1});> person.heads = 0;

0

> person.heads;

1

> delete person.heads;

false

> person.heads;

1

The following is a list of all ES5 additions to Object:

Property/method

Description

Object.getPrototypeOf(obj)

While in ES3 you have to guess what is the prototype of a given object using the method Object.prototype.isPrototypeOf(), in ES5 you can directly ask "Who is your prototype?"

> Object.getPrototypeOf([]) ===

Array.prototype;

true

Object.create(obj, descr)

Discussed in Chapter 6, Inheritance. Creates a new object, sets its prototype and defines properties of that object using property descriptors (discussed earlier).

> var parent = {hi: 'Hello'};

> var o = Object.create(parent, {

prop: {

value: 1

}

});

> o.hi;

"Hello"

It even lets you create a completely blank object, something you cannot do in ES3.

> var o = Object.create(null);

> typeof o.toString;

"undefined"

Object.getOwnPropertyDescriptor(obj, property)

Allows you to inspect how a property was defined. You can even peek into the built-ins and see all these previously hidden attributes.

> Object.getOwnPropertyDescriptor(Object.prototype, 'toString');

Object

configurable: true

enumerable: false

value: function toString() { [native code] }

writable: true

Object.getOwnPropertyNames(obj )

Returns an array of all own property names (as strings), enumerable or not. Use Object.keys() to get only enumerable ones.

> Object.getOwnPropertyNames(Object.prototype);

["constructor", "toString", "toLocaleString", "valueOf",...

Object.defineProperty(obj, descriptor)

Defines a property of an object using a property descriptor. See the discussion preceding this table.

Object.defineProperties(obj, descriptors)

The same as defineProperty(), but lets you define multiple properties at once.

> var glass = Object.defineProperties({}, {

"color": {

value: "transparent",

writable: true

},

"fullness": {

value: "half",

writable: false

}

});

> glass.fullness;

"half"

Object.preventExtensions(obj)

Object.isExtensible(obj)

preventExtensions() disallows adding further properties to an object and isExtensible() checks whether you can add properties.

> var deadline = {};

> Object.isExtensible(deadline);

true

> deadline.date = "yesterday";

"yesterday"

> Object.preventExtensions(deadline);

> Object.isExtensible(deadline);

false

> deadline.date = "today";

"today"

> deadline.date;

"today"

Attempting to add properties to a non-extensible object is not an error, but simply doesn't work:

> deadline.report = true;

> deadline.report;

undefined

Object.seal(obj)

Object.isSealed(obj )

seal() does the same as preventExtensions () and additionally makes all existing properties non-configurable.

This means you can change the value of an existing property, but you cannot delete it or reconfigure it (using defineProperty() won't work). So you cannot, for example, make an enumerable property non-enumerable.

Object.freeze(obj)

Object.isFrozen(obj)

Everything that seal() does plus prevents changing the values of properties.

> var deadline = Object.freeze(

{date: "yesterday"});

> deadline.date = "tomorrow";

> deadline.excuse = "lame";

> deadline.date;

"yesterday"

> deadline.excuse;

undefined

> Object.isSealed(deadline);

true

Object.keys(obj)

An alternative to a for-in loop. Returns only own properties (unlike for-in). The properties need to be enumerable in order to show up (unlike Object.getOwnPropertyNames()). The return value is an array of strings.

> Object.prototype.customProto = 101;

> Object.getOwnPropertyNames(

Object.prototype);

["constructor", "toString", ..., "customProto"]

> Object.keys(Object.prototype);

["customProto"]

> var o = {own: 202};

> o.customProto;

101

> Object.keys(o);

["own"]

Array

The Array constructor creates array objects:

> var a = new Array(1, 2, 3);

This is the same as the array literal:

> var a = [1, 2, 3]; //recommended

When you pass only one numeric value to the Array constructor, it's assumed to be the array length.

> var un = new Array(3);

> un.length;

3

You get an array with the desired length and if you ask for the value of each of the array elements, you get undefined.

> un;

[undefined, undefined, undefined]

There is a subtle difference between an array full of elements and an array with no elements, but just length:

> '0' in a;

true

> '0' in un;

false

This difference in the Array() constructor's behavior when you specify one versus more parameters can lead to unexpected behavior. For example, the following use of the array literal is valid:

> var a = [3.14];

> a;

[3.14]

However, passing the floating-point number to the Array constructor is an error:

> var a = new Array(3.14);

Range Error: invalid array length

The Array.prototype members

Property/method

Description

length

The number of elements in the array.

> [1, 2, 3, 4].length;

4

concat(i1, i2, i3,...)

Merges arrays together.

> [1, 2].concat([3, 5], [7, 11]);

[1, 2, 3, 5, 7, 11]

join(separator)

Turns an array into a string. The separator parameter is a string with comma as the default value.

> [1, 2, 3].join();

"1,2,3"

> [1, 2, 3].join('|');

"1|2|3"

> [1, 2, 3].join(' is less than ');

"1 is less than 2 is less than 3"

pop()

Removes the last element of the array and returns it.

> var a = ['une', 'deux', 'trois'];

> a.pop();

"trois"

> a;

["une", "deux"]

push(i1, i2, i3,...)

Appends elements to the end of the array and returns the length of the modified array.

> var a = [];

> a.push('zig', 'zag', 'zebra','zoo');

4

reverse()

Reverses the elements of the array and returns the modified array.

> var a = [1, 2, 3];

> a.reverse();

[3, 2, 1]

> a;

[3, 2, 1]

shift()

Like pop() but removes the first element, not the last.

> var a = [1, 2, 3];

> a.shift();

1

> a;

[2, 3]

slice(start_index, end_index)

Extracts a piece of the array and returns it as a new array, without modifying the source array.

> var a = ['apple', 'banana','js', 'css', 'orange'];

> a.slice(2,4);

["js", "css"]

> a;

["apple", "banana", "js", "css", "orange"]

sort(callback)

Sorts an array. Optionally accepts a callback function for custom sorting. The callback function receives two array elements as arguments and should return 0 if they are equal, a positive number if the first is greater and a negative number if the second is greater.

An example of a custom sorting function that does a proper numeric sort (since the default is character sorting):

function customSort(a, b) {

if (a > b) return 1;

if (a < b) return -1;

return 0;

}

Example use of sort():

> var a = [101, 99, 1, 5];

> a.sort();

[1, 101, 5, 99]

> a.sort(customSort);

[1, 5, 99, 101]

> [7, 6, 5, 9].sort(customSort);

[5, 6, 7, 9]

splice(start, delete_count, i1, i2, i3,...)

Removes and adds elements at the same time. The first parameter is where to start removing, the second is how many items to remove and the rest of the parameters are new elements to be inserted in the place of the removed ones.

> var a = ['apple', 'banana','js', 'css', 'orange'];

> a.splice(2, 2, 'pear', 'pineapple');

["js", "css"]

> a;

["apple", "banana", "pear", "pineapple", "orange"]

unshift(i1, i2, i3,...)

Like push() but adds the elements at the beginning of the array as opposed to the end. Returns the length of the modified array.

> var a = [1, 2, 3];

> a.unshift('one', 'two');

5

> a;

["one", "two", 1, 2, 3]

ECMAScript 5 additions to Array

Property/method

Description

Array.isArray(obj)

Tells if an object is an array because typeof is not good enough:

> var arraylike = {0: 101, length: 1};

> typeof arraylike;

"object"

> typeof [];

"object"

Neither is duck-typing (if it walks like a duck and quacks like a duck, it must be a duck):

typeof arraylike.length;

"number"

In ES3 you need the verbose:

> Object.prototype.toString.call([]) ===

"[object Array]";

true

> Object.prototype.toString.call

(arraylike) === "[object Array]";

false

In ES5 you get the shorter:

Array.isArray([]);

true

Array.isArray(arraylike);

false

Array.prototype.indexOf(needle, idx)

Searches the array and returns the index of the first match. Returns -1 if there's no match. Optionally can search starting from a specified index.

> var ar = ['one', 'two', 'one', 'two'];

> ar.indexOf('two');

1

> ar.indexOf('two', 2);

3

> ar.indexOf('toot');

-1

Array.prototype.lastIndexOf(needle, idx)

Like indexOf() only searches from the end.

> var ar = ['one', 'two', 'one', 'two'];

> ar.lastIndexOf('two');

3

> ar.lastIndexOf('two', 2);

1

> ar.indexOf('toot');

-1

Array.prototype.forEach(callback, this_obj)

An alternative to a for loop. You specify a callback function that will be called for each element of the array. The callback function gets the arguments: the element, its index and the whole array.

> var log = console.log.bind(console);

> var ar = ['itsy', 'bitsy', 'spider'];

> ar.forEach(log);

itsy 0 ["itsy", "bitsy", "spider"]

bitsy 1 ["itsy", "bitsy", "spider"]

spider 2 ["itsy", "bitsy", "spider"]

Optionally, you can specify a second parameter: the object to be bound to this inside the callback function. So this works too:

> ar.forEach(console.log, console);

Array.prototype.every(callback, this_obj)

You provide a callback function that tests each element of the array. Your callback is given the same arguments as forEach() and it must return true or false depending on whether the given element satisfies your test.

If all elements satisfy your test, every() returns true. If at least one doesn't, every() returns false.

> function hasEye(el, idx, ar) {

return el.indexOf('i') !== -1;

}

> ['itsy', 'bitsy', 'spider'].

every(hasEye);

true

> ['eency', 'weency', 'spider'].

every(hasEye);

false

If at some point during the loop it becomes clear that the result will be false, the loop stops and returns false.

> [1,2,3].every(function (e) { console.log(e);

return false;

});

1

false

Array.prototype.some(callback, this_obj)

Like every() only it returns true if at least one element satisfies your test:

> ['itsy', 'bitsy', 'spider'].

some(hasEye);

true

> ['eency', 'weency', 'spider'].

some(hasEye);

true

Array.prototype.filter(callback, this_obj)

Similar to some() and every() but it returns a new array of all elements that satisfy your test:

> ['itsy', 'bitsy', 'spider'].

filter(hasEye);

["itsy", "bitsy", "spider"]

> ['eency', 'weency', 'spider'].

filter(hasEye);

["spider"]

Array.prototype.map(callback, this_obj)

Similar to forEach() because it executes a callback for each element, but additionally it constructs a new array with the returned values of your callback and returns it. Let's capitalize all strings in an array:

> function uc(element, index, array) {

return element.toUpperCase();

}

> ['eency', 'weency', 'spider'].map(uc);

["EENCY", "WEENCY", "SPIDER"]

Array.prototype.reduce(callback, start)

Executes your callback for each element of the array. Your callback returns a value. This value is passed back to your callback with the next iteration. The whole array is eventually reduced to a single value.

> function sum(res, element, idx, arr) {

return res + element;

}

> [1, 2, 3].reduce(sum);

6

Optionally, you can pass a start value which will be used by the first callback call:

> [1, 2, 3].reduce(sum, 100);

106

Array.prototype.reduceRight(callback, start)

Like reduce() but loops from the end of the array.

> function concat(result_so_far, el) {

return "" + result_so_far + el;

}

> [1, 2, 3].reduce(concat);

"123"

> [1, 2, 3].reduceRight(concat);

"321"

Function

JavaScript functions are objects. They can be defined using the Function constructor, like so:

var sum = new Function('a', 'b', 'return a + b;');

This is a (generally not recommended) alternative to the function literal (also known as function expression):

var sum = function (a, b) {

return a + b;

};

Or, the more common function definition:

function sum(a, b) {

return a + b;

}

The Function.prototype members

Property/Method

Description

apply(this_obj, params_array)

Allows you to call another function while overwriting the other function's this value. The first parameter that apply() accepts is the object to be bound to this inside the function and the second is an array of arguments to be send to the function being called.

function whatIsIt(){

return this.toString();

}

> var myObj = {};

> whatIsIt.apply(myObj);

"[object Object]"

> whatIsIt.apply(window);

"[object Window]"

call(this_obj, p1, p2, p3, ...)

The same as apply() but accepts arguments one by one, as opposed to as one array.

length

The number of parameters the function expects.

> parseInt.length;

2

If you forget the difference between call() and apply():

> Function.prototype.call.length;

1

> Function.prototype.apply.length;

2

The call() property's length is 1 because all arguments except the first one are optional.

ECMAScript 5 additions to a function

Property/method

Description

Function.prototype.bind()

When you want to call a function that uses this internally and you want to define what this is. The methods call() and apply() invoke the function while bind() returns a new function. Useful when you provide a method as a callback to a method of another object and and you want this to be an object of your choice.

> whatIsIt.apply(window);

"[object Window]"

Boolean

The Boolean constructor creates Boolean objects (not to be confused with Boolean primitives). The Boolean objects are not that useful and are listed here for the sake of completeness.

> var b = new Boolean();

> b.valueOf();

false

> b.toString();

"false"

A Boolean object is not the same as a Boolean primitive value. As you know, all objects are truthy:

> b === false;

false

> typeof b;

"object"

Boolean objects don't have any properties other than the ones inherited from Object.

Number

This creates number objects:

> var n = new Number(101);

> typeof n;

"object"

> n.valueOf();

101

The Number objects are not primitive objects, but if you use any Number.prototype method on a primitive number, the primitive will be converted to a Number object behind the scenes and the code will work.

> var n = 123;

> typeof n;

"number"

> n.toString();

"123"

Used without new, the Number constructor returns a primitive number.

> Number("101");

101

> typeof Number("101");

"number"

> typeof new Number("101");

"object"

Members of the Number constructor

Property/method

Description

Number.MAX_VALUE

A constant property (cannot be changed) that contains the maximum allowed number.

> Number.MAX_VALUE;

1.7976931348623157e+308

Number.MIN_VALUE

The smallest number you can work with in JavaScript.

> Number.MIN_VALUE;

5e-324

Number.NaN

Contains the Not A Number number. The same as the global NaN.

> Number.NaN;

NaN

NaN is not equal to anything including itself.

> Number.NaN === Number.NaN;

false

Number.POSITIVE_INFINITY

The same as the global Infinity number.

Number.NEGATIVE_INFINITY

The same as -Infinity.

The Number.prototype members

Property/method

Description

toFixed(fractionDigits)

Returns a string with the fixed-point representation of the number. Rounds the returned value.

> var n = new Number(Math.PI);

> n.valueOf();

3.141592653589793

> n.toFixed(3);

"3.142"

toExponential(fractionDigits)

Returns a string with exponential notation representation of the number object. Rounds the returned value.

> var n = new Number(56789);

> n.toExponential(2);

"5.68e+4"

toPrecision(precision)

String representation of a number object, either exponential or fixed-point, depending on the number object.

> var n = new Number(56789);

> n.toPrecision(2);

"5.7e+4"

> n.toPrecision(5);

"56789"

> n.toPrecision(4);

"5.679e+4"

> var n = new Number(Math.PI);

> n.toPrecision(4);

"3.142"

String

The String() constructor creates string objects. Primitive strings are turned into objects behind the scenes if you call a method on them as if they were objects. Omitting new gives you primitive strings.

Creating a string object and a string primitive:

> var s_obj = new String('potatoes');

> var s_prim = 'potatoes';

> typeof s_obj;

"object"

> typeof s_prim;

"string"

The object and the primitive are not equal when compared by type with ===, but they are when compared with == which does type coercion:

> s_obj === s_prim;

false

> s_obj == s_prim;

true

length is a property of the string objects:

> s_obj.length;

8

If you access length on a primitive string, the primitive is converted to an object behind the scenes and the operation is successful:

> s_prim.length;

8

String literals work fine too:

> "giraffe".length;

7

Members of the String constructor

Property/method

Description

String.fromCharCode (code1, code2, code3, ...)

Returns a string created using the Unicode values of the input:

> String.fromCharCode(115, 99, 114,

105, 112, 116);

"script"

The String.prototype members

Property/method

Description

length

The number of characters in the string.

> new String('four').length;

4

charAt(position)

Returns the character at the specified position. Positions start at 0.

> "script".charAt(0);

"s"

Since ES5, it's also possible to use array notation for the same purpose. (This feature has been long supported in many browsers before ES5, but not IE)

> "script"[0];

"s"

charCodeAt(position)

Returns the numeric code (Unicode) of the character at the specified position.

> "script".charCodeAt(0);

115

concat(str1, str2, ....)

Return a new string glued from the input pieces.

> "".concat('zig', '-', 'zag');

"zig-zag"

indexOf(needle, start)

If the needle matches a part of the string, the position of the match is returned. The optional second parameter defines where the search should start from. Returns -1 if no match is found.

> "javascript".indexOf('scr');

4

> "javascript".indexOf('scr', 5);

-1

lastIndexOf(needle, start)

Same as indexOf() but starts the search from the end of the string. The last occurrence of a:

> "javascript".lastIndexOf('a');

3

localeCompare(needle)

Compares two strings in the current locale. Returns 0 if the two strings are equal, 1 if the needle gets sorted before the string object, -1 otherwise.

> "script".localeCompare('crypt');

1

> "script".localeCompare('sscript');

-1

> "script".localeCompare('script');

0

match(regexp)

Accepts a regular expression object and returns an array of matches.

> "R2-D2 and C-3PO".match(/[0-9]/g);

["2", "2", "3"]

replace(needle, replacement)

Allows you to replace the matching results of a regexp pattern. The replacement can also be a callback function. Capturing groups are available as $1, $2,...$9.

> "R2-D2".replace(/2/g, '-two');

"R-two-D-two"

> "R2-D2".replace(/(2)/g, '$1$1');

"R22-D22"

search(regexp)

Returns the position of the first regular expression match.

> "C-3PO".search(/[0-9]/);

2

slice(start, end)

Returns the part of a string identified by the start and end positions. If start is negative, the start position is length + start, similarly if the end parameter is negative, the end position is length + end.

> "R2-D2 and C-3PO".slice(4, 13);

"2 and C-3"

> "R2-D2 and C-3PO".slice(4, -1);

"2 and C-3P"

split(separator, limit)

Turns a string into an array. The second parameter, limit, is optional. As with replace(), search(), and match(), the separator is a regular expression but can also be a string.

> "1,2,3,4".split(/,/);

["1", "2", "3", "4"]

> "1,2,3,4".split(',', 2);

["1", "2"]

substring(start, end)

Similar to slice(). When start or end are negative or invalid, they are considered 0. If they are greater than the string length, they are considered to be the length. If end is greater than start, their values are swapped.

> "R2-D2 and C-3PO".substring(4, 13);

"2 and C-3"

> "R2-D2 and C-3PO".substring(13, 4);

"2 and C-3"

toLowerCase()

toLocaleLowerCase()

Transforms the string to lowercase.

> "Java".toLowerCase();

"java"

toUpperCase()

toLocaleUpperCase()

Transforms the string to uppercase.

> "Script".toUpperCase();

"SCRIPT"

ECMAScript 5 additions to String

Property/method

Description

String.prototype.trim()

Instead of using a regular expression to remove whitespace before and after a string (as in ES3), you have a trim() method in ES5.

> " \t beard \n".trim();

"beard"

Or in ES3:

> " \t beard \n".replace(/\s/g, "");

"beard"

Date

The Date constructor can be used with several types of input:

You can pass values for year, month, date of the month, hour, minute, second, and millisecond, like so:

> new Date(2015, 0, 1, 13, 30, 35, 505);

Thu Jan 01 2015 13:30:35 GMT-0800 (PST)

· You can skip any of the input parameters, in which case they are assumed to be 0. Note that month values are from 0 (January) to 11 (December), hours are from 0 to 23, minutes and seconds 0 to 59, and milliseconds 0 to 999.

· You can pass a timestamp:

· > new Date(1420147835505);

· Thu Jan 01 2015 13:30:35 GMT-0800 (PST)

· If you don't pass anything, the current date/time is assumed:

· > new Date();

· Fri Jan 11 2013 12:20:45 GMT-0800 (PST)

· If you pass a string, it's parsed in an attempt to extract a possible date value:

· > new Date('May 4, 2015');

· Mon May 04 2015 00:00:00 GMT-0700 (PDT)

Omitting new gives you a string version of the current date:

> Date() === new Date().toString();

true

Members of the Date constructor

Property/method

Description

Date.parse(string)

Similar to passing a string to new Date() constructor, this method parses the input string in an attempt to extract a valid date value. Returns a timestamp on success, NaN on failure:

> Date.parse('May 5, 2015');

1430809200000

> Date.parse('4th');

NaN

Date.UTC(year, month, date, hours, minutes, seconds, ms)

Returns a timestamp but in UTC (Coordinated Universal Time), not in local time.

> Date.UTC(2015, 0, 1, 13, 30, 35, 505);

1420119035505

The Date.prototype members

Property/method

Description/example

toUTCString()

Same as toString() but in universal time. Here's how Pacific Standard (PST) local time differs from UTC:

> var d = new Date(2015, 0, 1);

> d.toString();

"Thu Jan 01 2015 00:00:00 GMT-0800 (PST)"

> d.toUTCString();

"Thu, 01 Jan 2015 08:00:00 GMT"

toDateString()

Returns only the date portion of toString():

> new Date(2015, 0, 1).toDateString();

"Thu Jan 01 2010"

toTimeString()

Returns only the time portion of toString():

> new Date(2015, 0, 1).toTimeString();

"00:00:00 GMT-0800 (PST)"

toLocaleString()

toLocaleDateString()

toLocaleTimeString()

Equivalent to toString(), toDateString(), and toTimeString() respectively, but in a friendlier format, according to the current user's locale.

> new Date(2015, 0, 1).toString();

"Thu Jan 01 2015 00:00:00 GMT-0800 (PST)"

> new Date(2015, 0, 1).toLocaleString();

"1/1/2015 12:00:00 AM"

getTime()

setTime(time)

Get or set the time (using a timestamp) of a date object. The following example creates a date and moves it one day forward:

> var d = new Date(2015, 0, 1);

> d.getTime();

1420099200000

> d.setTime(d.getTime()+ 1000 * 60 * 60 * 24);

1420185600000

> d.toLocaleString();

"Fri Jan 02 2015 00:00:00 GMT-0800 (PST)"

getFullYear()

getUTCFullYear()

setFullYear(year, month, date)

setUTCFullYear(year, month, da te)

Get or set a full year using local or UTC time. There is also getYear() but it is not Y2K compliant, so use getFullYear() instead.

> var d = new Date(2015, 0, 1);

> d.getYear();

115

> d.getFullYear();

2015

> d.setFullYear(2020);

1577865600000

> d;

Wed Jan 01 2020 00:00:00 GMT-0800 (PST)

getMonth()

getUTCMonth()

setMonth(month, date)

setUTCMonth(month, date)

Get or set the month, starting from 0 (January):

> var d = new Date(2015, 0, 1);

> d.getMonth();

0

> d.setMonth(11);

1448956800000

> d.toLocaleDateString();

"12/1/2015"

getDate()

getUTCDate()

setDate(date)

setUTCDate(date)

Get or set the date of the month.

> var d = new Date(2015, 0, 1);

> d.toLocaleDateString();

"1/1/2015"

> d.getDate();

1

> d.setDate(31);

1422691200000

> d.toLocaleDateString();

"1/31/2015"

getHours()

getUTCHours()

setHours(hour, min, sec, ms)

setUTCHours(hour, min, sec, ms)

getMinutes()

getUTCMinutes()

setMinutes(min, sec, ms)

setUTCMinutes(min, sec, ms)

getSeconds()

getUTCSeconds()

setSeconds(sec, ms)

setUTCSeconds(sec, ms)

getMilliseconds()

getUTCMilliseconds()

setMilliseconds(ms)

setUTCMilliseconds(ms )

Get or set the hour, minutes, seconds, milliseconds, all starting from 0.

> var d = new Date(2015, 0, 1);

> d.getHours() + ':' + d.getMinutes();

"0:0"

> d.setMinutes(59);

1420102740000

> d.getHours() + ':' + d.getMinutes();

"0:59"

getTimezoneOffset()

Returns the difference between local and universal (UTC) time, measured in minutes. For example, the difference between PST (Pacific Standard Time) and UTC:

> new Date().getTimezoneOffset();

480

> 420 / 60; // hours

8

getDay()

getUTCDay( )

Returns the day of the week, starting from 0 (Sunday):

> var d = new Date(2015, 0, 1);

> d.toDateString();

"Thu Jan 01 2015"

> d.getDay();

4

> var d = new Date(2015, 0, 4);

> d.toDateString();

"Sat Jan 04 2015"

> d.getDay();

0

ECMAScript 5 additions to Date

Property/method

Description

Date.now()

A convenient way to get the current timestamp:

> Date.now() === new Date().getTime();

true

Date.prototype.toISOString()

Yet another toString().

> var d = new Date(2015, 0, 1);

> d.toString();

"Thu Jan 01 2015 00:00:00 GMT-0800 (PST)"

> d.toUTCString();

"Thu, 01 Jan 2015 08:00:00 GMT"

> d.toISOString();

"2015-01-01T00:00:00.000Z"

Date.prototype.toJSON()

Used by JSON.stringify() (refer to the end of this appendix) and returns the same as toISOString().

> var d = new Date();

> d.toJSON() === d.toISOString();

true

Math

Math is different from the other built-in objects because it cannot be used as a constructor to create objects. It's just a collection of static functions and constants. Some examples to illustrate the differences are as follows:

> typeof Date.prototype;

"object"

> typeof Math.prototype;

"undefined"

> typeof String;

"function"

> typeof Math;

"object"

Members of the Math object

Property/method

Description

Math.E

Math.LN10

Math.LN2

Math.LOG2E

Math.LOG10E

Math.PI

Math.SQRT1_2

Math.SQRT2

These are some useful math constants, all read-only. Here are their values:

> Math.E;

2.718281828459045

> Math.LN10;

2.302585092994046

> Math.LN2;

0.6931471805599453

> Math.LOG2E;

1.4426950408889634

> Math.LOG10E;

0.4342944819032518

> Math.PI;

3.141592653589793

> Math.SQRT1_2;

0.7071067811865476

> Math.SQRT2;

1.4142135623730951

Math.acos(x)

Math.asin(x)

Math.atan(x)

Math.atan2(y, x)

Math.cos(x)

Math.sin(x)

Math.tan(x)

Trigonometric functions

Math.round(x)

Math.floor(x)

Math.ceil(x)

round() gives you the nearest integer, ceil() rounds up, and floor() rounds down:

> Math.round(5.5);

6

> Math.floor(5.5);

5

> Math.ceil(5.1);

6

Math.max(num1, num2, num3, ...)

Math.min(num1, num2, num3, ...)

max() returns the largest and min() returns the smallest of the numbers passed to them as arguments. If at least one of the input parameters is NaN, the result is also NaN.

> Math.max(4.5, 101, Math.PI);

101

> Math.min(4.5, 101, Math.PI);

3.141592653589793

Math.abs(x)

Absolute value.

> Math.abs(-101);

101

> Math.abs(101);

101

Math.exp(x)

Exponential function: Math.E to the power of x.

> Math.exp(1) === Math.E;

true

Math.log(x)

Natural logarithm of x.

> Math.log(10) === Math.LN10;

true

Math.sqrt(x)

Square root of x.

> Math.sqrt(9);

3

> Math.sqrt(2) === Math.SQRT2;

true

Math.pow(x, y)

x to the power of y.

> Math.pow(3, 2);

9

Math.random()

Random number between 0 and 1 (including 0).

> Math.random();

0.8279076443185321

For an random integer in a range, say between 10 and 100:

> Math.round(Math.random() * 90 + 10);

79

RegExp

You can create a regular expression object using the RegExp() constructor. You pass the expression pattern as the first parameter and the pattern modifiers as the second.

> var re = new RegExp('[dn]o+dle', 'gmi');

This matches "noodle", "doodle", "doooodle", and so on. It's equivalent to using the regular expression literal:

> var re = ('/[dn]o+dle/gmi'); // recommended

Chapter 4, Objects and Appendix D, Regular Expressions contains more information on regular expressions and patterns.

The RegExp.prototype members

Property/method

Description

global

Read-only. true if the g modifier was set when creating the regexp object.

ignoreCase

Read-only. true if the i modifier was set when creating the regexp object.

multiline

Read-only. true if the m modifier was set when creating the regexp object

lastIndex

Contains the position in the string where the next match should start. test() and exec() set this position after a successful match. Only relevant when the g (global) modifier was used.

> var re = /[dn]o+dle/g;

> re.lastIndex;

0

> re.exec("noodle doodle");

["noodle"]

> re.lastIndex;

6

> re.exec("noodle doodle");

["doodle"]

> re.lastIndex;

13

> re.exec("noodle doodle");

null

> re.lastIndex;

0

source

Read-only. Returns the regular expression pattern (without the modifiers).

> var re = /[nd]o+dle/gmi;

> re.source;

"[nd]o+dle"

exec(string)

Matches the input string with the regular expression. A successful match returns an array containing the match and any capturing groups. With the g modifier, it matches the first occurrence and sets the lastIndex property. Returns null when there's no match.

> var re = /([dn])(o+)dle/g;

> re.exec("noodle doodle");

["noodle", "n", "oo"]

> re.exec("noodle doodle");

["doodle", "d", "oo"]

The arrays returned by exec() have two additional properties: index (of the match) and input (the input string being searched).

test(string)

Same as exec() but only returns true or false.

> /noo/.test('Noodle');

false

> /noo/i.test('Noodle');

true

Error objects

Error objects are created either by the environment (the browser) or by your code.

> var e = new Error('jaavcsritp is _not_ how you spell it');

> typeof e;

"object"

Other than the Error constructor, six additional ones exist and they all inherit Error:

· EvalError

· RangeError

· ReferenceError

· SyntaxError

· TypeError

· URIError

The Error.prototype members

Property

Description

name

The name of the error constructor used to create the object:

> var e = new EvalError('Oops');

> e.name;

"EvalError

"

message

Additional error information:

> var e = new Error('Oops... again');

> e.message;

"Oops... again"

JSON

The JSON object is new to ES5. It's not a constructor (similarly to Math) and has only two methods: parse() and stringify(). For ES3 browsers that don't support JSON natively, you can use the "shim" from http://json.org.

JSON stands for JavaScript Object Notation. It's a lightweight data interchange format. It's a subset of JavaScript that only supports primitives, object literals, and array literals.

Members of the JSON object

Method

Description

parse(text, callback)

Takes a JSON-encoded string and returns an object:

> var data = '{"hello": 1, "hi": [1, 2, 3]}';

> var o = JSON.parse(data);

> o.hello;

1

> o.hi;

[1, 2, 3]

The optional callback lets you provide your own function that can inspect and modify the result. The callback takes key and value arguments and can modify the value or delete it (by returning undefined).

> function callback(key, value) {

console.log(key, value);

if (key === 'hello') {

return 'bonjour';

}

if (key === 'hi') {

return undefined;

}

return value;

}

> var o = JSON.parse(data, callback);

hello 1

0 1

1 2

2 3

hi [1, 2, 3]

Object {hello: "bonjour"}

> o.hello;

"bonjour"

> 'hi' in o;

false

stringify(value, callback, white)

Takes any value (most commonly an object or an array) and encodes it to a JSON string.

> var o = {

hello: 1,

hi: 2,

when: new Date(2015, 0, 1)

};

> JSON.stringify(o);

"{"hello":1,"hi":2,"when":"2015-01-01T08:00:00.000Z"}"

The second parameter lets you provide a callback (or a whitelist array) to customize the return value. The whitelist contains the keys you're interested in:

JSON.stringify(o, ['hello', 'hi']);

"{"hello":1,"hi":2}"

The last parameter helps you get a human-readable version. You specify the number of spaces as a string or a number.

> JSON.stringify(o, null, 4);

"{

"hello": 1,

"hi": 2,

"when": "2015-01-01T08:00:00.000Z"

}"