JavaScript Reference

String

String.fromCharCode(Unicode values)

String.fromCharCode(65, 66, 67);
"ABC"

[String].length

"ABC".length;
3

[String].charAt(integer > -1 and < string length)

"ABC".charAt(1);
"B"

[String].charCodeAt(integer > -1 and < string length)

"ABC".charCodeAt(1);
66

[String].concat(strings)

"foo".concat("fizz", "buzz");
"foofizzbuzz"

[String].indexOf(search string, start at)

Return the index of the first location of the search string or -1 if it is not found.

Optional search start index defaults to 0.

"ABACAB".indexOf("B");
1
"ABACAB".indexOf("CAB");
3
"ABACAB".indexOf("B", 2);
5

[String].lastIndexOf(search string, start at)

Return the index of the last location of the search string or -1 if it is not found.

Optional search start index defaults to the string length.

"ABACAB".lastIndexOf("B");
5
"ABACAB".lastIndexOf("B", 4);
1

[String].match(regular expression)

Return an array of results matched by the regular expression.

"ABACAB".match(/[BC]/gi);
["B", "C", "B"]

[String].replace(regular expression, replacement string)

Return a string with parts matched by a regular expression replaced by the second parameter.

"ABACAB".replace(/AB/gi, "D");
["DACD"]

[String].search(regular expression)

Works just like indexOf() but uses regular expressions.

"ABACAB".search(/[BC]/gi);
1

[String].slice(start slice, end slice)

Return a section of a string between two indices.

If the optional second parameter is omitted, it defaults to the end of the string.

If the second parameter is negative, it is subtracted from the string length.

If the start index is negative, it is counted from the end of the string.

"ABACAB".slice(4);
"AB"
"ABACAB".slice(1, 4);
"BAC"
"ABACAB".slice(2, -1);
"ACA"
"ABACAB".slice(-3);
"CAB"

[String].split(delimiter)

Returns an array derived from a string divided by a delimiter.

"foo, bar, fizz".split(", ");
["foo", "bar", "fizz"]

[String].substr(start index, length)

Return a section of a string starting at one index ending at the length plus the start index.

If the optional second parameter is omitted, it defaults to the end of the string.

"ABACAB".substr(3);
"CAB"
"ABACAB".substr(1, 4);
"BACA"

[String].substring(start slice, end slice)

Return a section of a string between two indices.

If the optional second parameter is omitted, it defaults to the end of the string.

This is almost identical to slice() which should probably be used instead of substring().

"ABACAB".substring(3);
"CAB"
"ABACAB".substring(1, 4);
"BAC"

[String].toLowerCase()

"ABACAB".toLowerCase();
"abacab"

[String].toUpperCase()

"Abacab".toUpperCase();
"ABACAB"

Array

[Array].length

[4, 8, 15, 16, 23, 42].length;
6

Array Mutator Methods

These methods alter the original array.

[Array].pop()

Removes the last element of an array and returns it.

[4, 8, 15, 16, 23, 42].pop();
42

[Array].push(x)

Adds an element to the end of an array and returns the new length.

[4, 8, 15, 16, 23].push(42);
6

[Array].reverse()

Reverses the order of an array and returns a reference to it.

[4, 8, 15, 16, 23, 42].reverse();
[42, 23, 16, 15, 8, 4]

[Array].shift()

Removes the first element of an array and returns it.

[4, 8, 15, 16, 23, 42].shift();
4

[Array].sort(optional compare function)

Sorts an array alphabetically, or according to the compare function.

[4, 8, 15, 16, 23, 42].sort();
[15, 16, 23, 4, 42, 8]
[4, 8, 15, 16, 23, 42].sort(function (a, b) {return b - a; });
[42, 23, 16, 15, 8, 4]

[Array].splice(start index, number of elements to remove, elements to add)

Starting at the specified index, removes and returns a number of elements and optionally adds new elements.

[4, 8, 815, 23, 42].splice(2, 1, 15, 16);
815

[Array].unshift(elements to add to the array)

Adds elements to the beginning of an array and returns the new length.

[15, 16, 23, 42].unshift(4, 8);
6

Array Accessor Methods

These methods do not alter the original array.

[Array].concat(elements to add to the array)

Return an array the is a combination of the original array plus all parameters.

[4, 8].concat([15, 16], [23], 42);
[4, 8, 15, 16, 23, 42]

[Array].join(delimiter)

Returns a string converted from an array.

[4, 8, 15, 16, 23, 42].join(' foo ');
"4 foo 8 foo 15 foo 16 foo 23 foo 42"

[Array].slice(begin index, end index)

Returns a portion of an array.

If the second parameter is not included, it defaults to the end of the array.

[4, 8, 15, 16, 23, 42].slice(2, 4);
[15, 16]

[Array].toString()

Returns a string representation of an array.

[4, 8, 15, 16, 23, 42].toString();
"4,8,15,16,23,42"

Math

Properties

Math.E

Euler's number ≈ 2.718

Math.LN2

Natural log of 2 ≈ 0.693

Math.LN10

Natural log of 10 ≈ 2.303

Math.LOG2E

Base 2 log of e ≈ 1.443

Math.LOG10E

Base 10 log of e ≈ 0.434

Math.PI

Pi ≈ 3.14159

Math.SQRT1_2

Square root of 1/2 ≈ 0.707

Math.SQRT2

Square root of 2 ≈ 1.414

Math Methods

Math.abs(x)

Absolute value

Math.acos(x)

Arccosine

Math.asin(x)

Arcsine

Math.atan(x)

Arctangent

Math.atan2(x, y)

Arctangent of the quotient of arguments

Useful for determining the angle between two points.

function angleBetween2Points(x1, y1, x2, y2) {
    return (Math.atan2(x2 - x1, y2 - y1) * 180 / Math.PI) + '°';
}

Math.ceil(x)

Returns the smallest integer greater than or equal to a number.

Math.ceil(3.14159);
4

Math.cos(x)

Cosine

Math.exp(x)

Returns Ex

Math.floor(x)

Returns the largest integer less than or equal to a number.

Math.floor(3.14159);
3

Math.log(x)

Natural log

Math.max(numbers)

Math.max(1, -50, 7);
7

Math.min(numbers)

Math.min(1, -50, 7);
-50

Math.pow(x, y)

Returns xy

Math.pow(5, 2);
25

Math.random()

Returns a random floating-point number between 0 and 1

(Math.random() > 0.5) ? 'heads' : 'tails';
"tails"
Math.ceil(Math.random() * 6);
5

Math.round(x)

Returns the value of a number rounded to the nearest integer. If the fractional portion of number is 0.5 or greater, the argument is rounded to the next higher integer.

Math.round(1.2354 * 100) / 100;
1.24

Math.sin(x)

Sine

Math.sqrt(x)

Square root

Math.tan(x)

Tangent

Date

Constructor

new Date();
Fri Apr 04 2014 13:24:06 GMT-0400 (Eastern Daylight Time)
new Date(0);
Wed Dec 31 1969 19:00:00 GMT-0500 (Eastern Standard Time)
new Date(24 * 60 * 60 * 1000);
Thu Jan 01 1970 19:00:00 GMT-0500 (Eastern Standard Time)
new Date("Wed Dec 31 1969 19:00:00 GMT-0500 (Eastern Standard Time)");
Wed Dec 31 1969 19:00:00 GMT-0500 (Eastern Standard Time)
new Date(2014, 1, 28, 11, 34, 59);
Fri Feb 28 2014 11:34:59 GMT-0500 (Eastern Standard Time)
+(new Date(2014, 1, 28, 11, 34, 59));
1393605299000

Date Methods

Date.parse(date string)

Returns milliseconds since 1/1/1970 based on the parse date string.

Date.parse("Aug 9, 1995");
Date.parse("Aug 9, 1995");
Date.parse("1995/8/9");
807940800000
Date.parse("Wed, 09 Aug 1995 00:00:00 GMT");
807926400000
Date.parse("Wed, 09 Aug 1995 00:00:00 EST");
807944400000
Date.parse("Wed, 09 Aug 1995 00:00:00 GMT-0400");
807940800000

Date.UTC(year, month, date, hour, min, sec, ms)

Returns milliseconds since 1/1/1970 based on parameter values.

Only year and month are required.

Date.UTC(96, 11, 1, 0, 0, 0);
849398400000
new Date(Date.UTC(96, 11, 1, 0, 0, 0));
Sat Nov 30 1996 19:00:00 GMT-0500 (Eastern Standard Time)
Date.UTC(96, 11);
849398400000

Date Instance Methods

All methods in the section have a corresponding UTC method (e.g. getUTCFullYear()) that instead of returning values for local time, they return to universal time. They also have a setter (e.g. setFullYear()) that changes the value accordingly. And yes, each setter has a UTC version (e.g. setUTCFullYear()).

[Date].getDate()

Returns day of the month (1-31)

(new Date()).getDate();
4

[Date].getDay()

Returns day of the week (0-6)

(new Date()).getDay();
5
function dayName(iDay) {
    var dayNames = ["Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday"];
    return dayNames[iDay];
}

[Date].getFullYear()

Returns 4-digit year.

(new Date()).getFullYear();
2014

[Date].getHours()

Returns hour (0-23)

(new Date()).getHours();
15
function hour12(hours) {
    if (hours >= 12) {
        if (hours >= 13) {
            return (hours - 12) + ' PM';
        }
        return hours + ' PM';
    }
    return hours + ' AM';
}

[Date].getMilliseconds()

Returns milliseconds (0-999)

(new Date()).getMilliseconds();
3

[Date].getMinutes()

Returns minutes (0-59)

(new Date()).getMinutes();
55

[Date].getMonth()

Returns day of the month (0-11)

(new Date()).getMonth();
3
function monthName(iMonth) {
    var monthNames = ["January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December"];
    return monthNames[iMonth];
}

[Date].getSeconds()

Returns seconds (0-59)

(new Date()).getSeconds();
4

[Date].getTime()

Returns milliseconds since 1/1/1970.

(new Date()).getTime();
1396641304003

You can also cast a date as an integer using the unary operator.

+(new Date());

[Date].getTimezoneOffset()

Returns the time-zone offset in minutes for the current locale.

(new Date()).getTimezoneOffset();
240

Date Conversion Getters

[Date].toDateString()

Returns the date portion of a Date object in American English.

(new Date()).toDateString();
"Fri Apr 04 2014"

[Date].toJSON()

Returns a JSON representation of a Date object.

(new Date()).toJSON();
"2014-04-04T20:25:25.237Z"

[Date].toString()

Returns a string representing the a Date object.

(new Date()).toString();
"2014-04-04T20:25:25.237Z"

[Date].toTimeString()

Returns the time portion of a Date object in American English.

(new Date()).toTimeString();
"16:37:24 GMT-0400 (Eastern Standard Time)"

[Date].toUTCString()

Returns a Date object as a string converted to UTC.

(new Date()).toUTCString();
"Fri, 04 Apr 2014 20:43:56 GM"

Global Functions

eval(string of JavaScript code)

Executes a string as JavaScript code. You should probably never use this.

eval("1 + 3");
4

isFinite(x)

isFinite(Infinity);
false
isFinite(5);
true

isNaN(x)

isNaN("45");
false
isNaN("ABACAB");
true

From StackOverflow

function isNumber(n) {
    return !isNaN(parseFloat(n)) && isFinite(n);
}

parseFloat(x)

parseFloat("314e-2");
3.14

parseInt(string, radix)

Converts a string to an integer, dropping the decimal portion and converting from the radix base.

parseInt('123.9', 10);
123
parseInt('efefef', 16);
15724527
parseInt('100', 2);
4

decodeURI(x)

decodeURI("http://www.restfulmvc.com/test%20uri/?a=http%3A%2F%2Fwww.google.com%2F");
"http://www.restfulmvc.com/test uri/?a=http%3A%2F%2Fwww.google.com%2F"

decodeURIComponent(x)

decodeURIComponent("http%3A%2F%2Fwww.google.com%2F");
"http://www.google.com/"

encodeURI(x)

encodeURI("http://www.restfulmvc.com/test uri/?a=http://www.google.com/");
"http://www.restfulmvc.com/test%20uri/?a=http://www.google.com/"

encodeURIComponent(x)

encodeURIComponent("http://www.google.com/");
"http%3A%2F%2Fwww.google.com%2F"
encodeURI("http://www.restfulmvc.com/test uri/?a=") + encodeURIComponent("http://www.google.com/");
"http://www.restfulmvc.com/test%20uri/?a=http%3A%2F%2Fwww.google.com%2F"

Number

Properties

Number.MAX_VALUE

Number.MAX_VALUE;
1.7976931348623157e+308

Number.MIN_VALUE

Number.MIN_VALUE;
5e-324

Number Instance Methods

[Number].toExponential(digits after the decimal point)

0.0000000000000000000000000000000006626.toExponential();
"6.626e-34"
(602214130000000000000000).toExponential(3);
"6.022e+23"

[Number].toFixed(digits after the decimal point)

Return a string representation of a floating-point number rounded to the exact number of digits after the decimal point.

Optional parameter defaults to 0.

(1.9).toFixed();
"2"
(5).toFixed(2);
"5.00"

[Number].toPrecision(significant digits)

Return a string representation of a floating-point number rounded or padded to the exact number of significant digits.

Significant digits must be > 0 and < 22.

Math.PI.toPrecision(5);
"3.1416"
40075.16.toPrecision(2);
"4.0e+4"
(0.1).toPrecision(5);
"0.10000"

[Number].toString(radix)

Return a string representation of a number in the base of the radix value.

Radix must be > 1 and < 37.

(100).toString(2);
"1100100"
(0xff).toString(10);
"255"

Object

[Object].hasOwnProperty(key)

Returns a boolean indicating whether the object has the specified property.

var key, obj = {'a': '1', 'b': '2'};
for (key in obj) {
    if (obj.hasOwnProperty(key)) {
        // Do something with obj[key]
    }
}

Regular Expressions

[RegEx].exec(search string)

Returns the first match of a regular expression in a string.

/[BC]/gi.exec("ABACAB");
["B"]

[RegEx].test(search string)

Returns the first match of a regular expression in a string.

/[BC]/gi.test("ABACAB");
true