Logo
Copyright © 2009 BrandsPatch LLC

JavaScript Quick Reference/Cheatsheet

An extended version of this JavaScript cheatsheet is available in ETKit Companion - an all-color compendium of cheatsheets covering the essentials of CSS, HTML, JavaScript, PHP and SQL.

A PDF version of this cheatsheet is available for download.

Code Structure Click to expand
var...
//Global variable declarations
function funcA([param1,param2...])
{
var...
//Local variable declarations - visible in nested functions

[function innerFuncA([iParam1,iparam2...])
{
var...
//Variables local to innerFuncA
//Your code here
}]

aName="ETKit - All my tools...in one place";
}
Nomenclature Rules Click to expand

Function and variable names can consist of any alphanumeric character. $ and _ are allowed. The first character cannot be numeric. Many extended ASCII characters are allowed. There is no practical limit on name length. Names are case-sensitive.

If two or more variables or functions or a variable & a function are declared with the same name the last declaration obliterates all previous ones. Using a keyword as a variable or function name obliterates that keyword.

Visibility & Scope Click to expand

Assignments without the use of the var keyword result in a new global variable of that name being created.

Variables declared with the var keyword outwith the body of a function are global. Variables declared with the var keyword inside the body of a function are local to that function. Local variables are visible to all nested functions.

Local entities hide globals bearing the same name.

Variable Types Click to expand
string:var s = "ETKit"
number:var n = 3.14159, 100, 0...
boolean:var b = false|true
object:var d = new Date()
function:var Greet = function sayHello(){alert("Say Hello!")}

JavaScript is a weakly typed language - i.e. a simple assignment is sufficient to change the variable type. The typeof keyword can be used to check the current variable type.

Special Values Click to expand
The special values false, Infinity, NaN, null, true & undefined are recognized. null is an object. Infinity and NaN are numbers.
Operators Click to expand

There are four classes of operator in JavaScript - arithmetic, comparison, logical and bitwise

Operator Example Result Operator Example Result
+ 3 + 2
" ETKit " + " Chameleon "
5
" ETKit Chameleon "
- 3 - 2 1
× 3*2 6 ÷ 3/2 1.5
% 3%2 1 ++,-- i=2;j=4
i++;j--; 1
++i;--j; 2
1 Evaluates after use.
2 Evaluates before use
3
== 3 ==" 3 "
2 == 3
true
false
=== 3 ==" 3 "
3 == 3
false
true
< 2 < 3
" a "<" A "
true
false
<= 2 <= 3 true
> 2 > 3 false > 2 >= 3 false
= i = 5 Assignment += i += 1 1 added to i
-= i -= 1 1 subtracted from i *= i *= 2 i multiplied by 2
/= i /= 2 i divided by 2 %= i %= 2 Integer division of i by 2
i = 2 ; j = 5 ;          
&&(AND) ( i <= 2 ) && ( j < 7 ) true ||(OR) ( i % 2 > 0 ) || ( j % 2 == 0 ) false
! (NOT) ( i == 2 ) && !( j % 2 == 0 ) true XOR ( a || b ) && !( a && b ) JavaScript has no native logical XOR operator. Use this instead.
i = 2 ; j = 7 ;          
& (bitwise and) i & j 2 | (bitwise or) i | j 7
^ (bitwise xor) i ^ j 5 ~ (bitwise not) ~ i -3
<< (left shift) 2 << 1 4 >> (right shift) 2 >> 1 1
Internal Functions Click to expand
decodeURI - reverses encodeURI
decodeURIComponent - reverses encodeURIComponent
encodeURI - encodes everything except :/?!&;,~@=+$.*()#_     and alphanumeric characters.
encodeURIComponent - encodes everything except !~.*()_ and alphanumerics
escape - does not encode @+-*._ and alphanumerics
unescape - reverses escape
eval - evaluates JavaScript expressions
isNaN - returns true if the argument is not a number
isFinite(2/0) returns false
parseInt(31.5°) returns 31
parseFloat(31.5°) returns 31.5
Array Object Click to expand
length - number of elements in the array
concat(arg1,arg2..) - concatenates argument arrays & returns a new array
join(arg) - returns elements as a string separated by argument. Uses , if no argument is supplied.
pop - suppresses & return last array element
push(arg1,arg2...) - adds arguments as new elements to the end of the array and returns the new array length
reverse - inverts order of array elements
shift - suppresses and returns first array element
slice(apos,bpos) - returns array slice. 1st argument is start position. 2nd argument is end position + 1
sort - sorts the array using the function provided in the argument. If no argument is supplied an alphanumeric sort is performed
splice(index,count,e1,e2...) - inserts e1,e2... starting at position index after removing count elements in the original array. If count is not supplied it is assumed to be zero.
unshift(arg1,arg2...) - adds elements to the start of the array and returns the new length
Date Object Click to expand
get#
getUTC#
set#
setUTC#
where # is one of Date, Day, FullYear, Hours, Milliseconds, Minutes, Months, Seconds, Time, TimezoneOffset
toDateString - the date in English
toGMTString - the date & time in English
toLocaleDateString - the date in the locale language
toLocaleString - the date & time in the locale language
toLocaleTimeString - the time in the locale language
toTimeString - time in English
toUTCString - the date & time in UTC, English
valueOf - the number of milliseconds elapsed since midnight 1st January 1970
Math Object Click to expand
E - the number e
LN10 - natural logarithm of 10
LN2 - natural logarithm of 2
LOG10E - log to the base 10 of e
LOG2E - log to the base 2 of e
PI - number π
SQRT1_2 - square root of 0.5
SQRT2 - square root of 2
abs(arg) - absolute value of argument
#(arg) - trigonometric functions
  a#(arg) - inverse trigonometric functions
where # is one of cos, sin or tan.
ceil(arg) - smallest whole number >=arg
floor(arg) - biggest whole number <=arg
log(arg) - natural logarithm of arg
max(n1,n2) - bigger of n1 and n2
min(n1,n2) - smaller of n1 and n2
pow(a,b) - ab
random - random number between 0 and 1
round(arg) - arg rounded down to the closest integer
sqrt(arg) - the square root of arg
Number Object Click to expand
MAX_VALUE - ca 1.7977E+308
MIN_VALUE - ca -5E-324
NEGATIVE_INFINITY - number smaller than MIN_VALUE
POSITIVE_INFINITY - number greater than MAX_VALUE
n.toExponential(m) - n in scientific notation with m decimal places
n.toFixed() - n rounded to closest whole number
n.toPrecision(m) - n rounded to m figures
In JavaScript hexadecimal numbers are designated by the prefix 0x or 0X. Octal numbers should start with a 0
String Object Click to expand
length - number of characters in the string
s.charAt(n) - the nth character in s. The shotcut notation s[n] can be used in some browsers but not all, notably not in Internet Explorer
s.charCodeAt(n) - code of the character s[n]
s.fromCharCode(n1,n2) - string built from Unicode values n1,n2...
s1.indexOf(s2,n) - location of s2 in s1 starting from position n. 0 is assumed if no n is specified.
s1.lastIndexOf(s2) - location of s2 in s1 starting from the end
s.substr(n1,n2) - returns n2 characters starting from s[n1]. If no n2 is specified returns to the end of the string. Negative n1 implies return from the end of the string. For instance "ETKit".substr(-3,3) would return "kit"
s.toLowerCase - lowercase version of s
s.toUpperCase - uppercase version of s
Escape Sequences Click to expand
\n - new line
\r - carriage return
\t - tab character
\\ - \ character
\' - apostrophe
\" - quote
\uNNNN - Unicode at NNNN. e.g. \u25BA gives ►
JavaScript in HTML Click to expand

External JavaScript

<script type ="text/javascript" [ defer ="defer" ] src ="http://www.etkit.com/script.js" </script>

Inline JavaScript

<script type="text/javascript">
//your code here
</script>
Comments in JavaScript Click to expand

Single Line Comments

//Your comments here

Multiline Comments

/*Comment spanning two or
   more lines*/
Conditional Execution Click to expand
if (Condition) CodeIfTrue;else CodeIfFalse - note the semicolon before else. Multiline CodeIf# statements must be wrapped in braces, {}
switch(variable)
{
case Value1:Code;
break;
case Value2:Code;
break;
....
default:Code
}
Variable boolean, number, string or date
(Condition)?(CodeIfTrue):(CodeIfFalse) //The parentheses are not necessary but advisable.
Example:return (isNaN(i))?"Yes":"No";
Error Handling Click to expand

Method One - The onerror Event

<script type="text/javascript">
function whenError(msg,url,lineNo)
{
//Use the parameters to supply meaningful error messages
}
window.onerror = whenError
</script>

Place this code in a separate <script>..</script> tag pair to trap errors occurring in other scripts. This technique blocks errors without taking any corrective action.

Method Two - try...finally

function showLogValue(num)
{
var s = "NoError";
try
{
if (num < 0) throw "badnum";
if (num = 0) throw "zero";
}
catch(err)
{
s = err;
case "badnum":num=-num;
break;
case "zero":num=1;
break;
}
[finally
{
alert(s,Math.log(num));
}
]
}
The finally block is optional. The two methods can be used in concert.
Looping Click to expand
function whileLoop(num)
{
while (num>0)
{
alert(num);
num--;
}
}
function doLoop(num)
{
do
{
alert(num);
num--;
}while(num>0);
}
function forLoop(num)
{
var i;
for(i=0;i<num;i++)
{
alert(num);
}
}

break causes immediate termination of the loop. continue forces the next iteration of the loop without execution of any statements in the loop block that follow continue.

function forInLoop()
{
var s,x;
for(x in  document)
{
s=x + "=" + document[x]
alert(s);
}
}

The last example is best tried out in Opera which offers the option of stopping the script at each alert. In place of document any JavaScript object or an array can be used to loop through its properties/elements.

return Click to expand

return causes immediate termination of the JavaScript function. If no value is returned, or if return is missing the function return type is undefined.

document Object Click to expand
body - the body of the document
cookie - read/write the document cookies
domain - where was the document served from?
forms[] - array of all forms in the document
images[] - array of all images in the document
referrer - who pointed to this document?
URL - the URL of the document
getElementById(id) - returns element bearing the ID id
getElementsByName(name) - returns array of elements named name
getElementsByTagName(tag) - returns array of all elements of type tag
write - writes plain or HTML text to the document
onload - occurs when the document is loaded
onunload - occurs when the user browses away, the tab is closed etc.
element Object Click to expand

By element we mean any HTML element retrieved using the document. getElementBy# methods.

attributes - all element attributes in an array
className - the CSS style assigned to the element
id - the id assigned to the element
innerHTML - the HTML content of the element
innerText - the content of the element shorn of all HTML tags. Does not work in Firefox
offset# - element dimensions (# = Height/Width) or location (# = Left/Right) in pixels
ownerDocument - the document that owns the element
style - CSS style declaration
tagName - element tag type. Always returned in uppercase
textConent - the Firefox equivalent of innerText
location Object Click to expand
host - the URL of the site serving up the document
href - the entire URL to the document
pathname - the path to the document on the host
protocol - the protocol used, e.g. http
reload(fromCache) - reloads the document. Reloads from the cache if fromCache is true
replace(url) - replaces the document with the one at url. Discards document entry in browser history
screen Object Click to expand
height - screen height in pixels
width - screen width in pixels
window Object Click to expand
alert(msg) - displays a dialog with msg
clearInterval(id) - clears interval id set by setInterval
clearTimeout(id) - clears timeout id set by setTimeout
confirm(msg) - displays a confirmation dialog with the text in msg
print() - prints the contents of the window
prompt(msg,[default]) - seeks user input, optionally initially set to default
setInterval(expr,interval) - causes the function at expr to be evaluated at intervals of interval milliseconds. Passing parametsr to the function to be evaluated is not widely supported
setTimeout(expr,time) - similar to setInterval but non-repeating