You are on page 1of 2

JavaScript Quick Reference Card1.

03

/ 3/2 1.5 slice returns array slice. 1st arg is start position. 2nd arg
is last position + 1
% 3%2 1 sort alphanumeric sort if no argument. Pass sort
++ i = 2; 3 function as argument for more specificity.
i++1, ++i2 splice discard and replace elements
-- i = 2; 1 unshift append elements to start & return new length
Copyright, 2007-2008 BrandsPatch LLC i--1, --i2 Date Object
http://www.explainth.at == 3 = '3' true get#
Color key overleaf == 2 == 3 false getUTC#
Code Structure === 3 === 3 true set#
var ... 3 === '3' false setUTC#
//Global variable declarations where # is one of Date, Day, FullYear, Hours,
< 2<3 true
function funcA([param1,param2,...]) 'a' < 'A' false Milliseconds, Minutes, Month, Seconds, Time,
{ TimezoneOffset
var ... <= 2 <= 3 true
toDateString the date in English.
//Local variable declarations visible in nested
functions > 2>3 false toGMTString the date & time in English.
>= 2>3 false toLocaleDateString the date in the locale language.
[function innerFuncA([iparam1,iparam2...]) toLocaleString date & time in the locale language.
{ = i=2 i is assigned
var ... the value 2 toLocaleTimeString time in the locale language.
//Variables local to innerFuncA toTimeString time in English.
+= i+=1 3
//your code here toUTCString date & time in UTC, English
}] -= i-=1 2
valueOf milliseconds since midnight 01 January 1970,
i*= i*=3 6 UTC
aName='ExplainThat!'; Math Object
//implicit global variable creation /= i/=2 3
//your code here E, LN10, LN2, LOG10E, LOG2E, PI, SQRT1_2, SQRT2
%= i%=2 1 abs absolute value
}
Nomenclature Rules i = 2;j = 5; #(n) - trigonometric functions
Function and variable names can consist of any && (AND) (i <= 2) && (j < 7) true a#(n) - inverse trigonometric functions
alphanumeric character. $ and _ are allowed. The first where # is one of cos, sin or tan
character cannot be numeric. Many extended ASCII || (OR) (i%2 > 0) || (j%2 == 0) false
ceil(n) smallest whole number >= n
characters are allowed. There is no practical limit on
! (NOT) (i==2) && !(j%2 == 0) true
name length. Names are case-sensitive. exp(n) returns en
If two or more variables or functions or a variable & a i = 2;j = 7; floor(n) biggest whole number <= n
function are declared with the same name the last & (bitwise) i&j 2 log(n) logarithm of n to the base e
declaration obliterates all previous ones. Using a
max(n1,n2) bigger of n1 and n2
keyword as a variable or function name obliterates that | (bitwise) i|j 7
keyword. min(n1,n2) smaller of n1 and n2
^(XOR) i^j 5
Visibility & Scope pow(a,b) - ab
Assignments without the use of the var keyword result << 2<<1 4 random random number between 0 and 1
in a new global variable of that name being created. >> 2>>1 1 round(n) n rounded down to closest integer
Variables declared with the var keyword outwith the sqrt(n) square root of n
>>> i=10 (binary 1010) 23
body of a function are global. Variables declared with i>>>2 Number Object
the var keyword inside the body of a function are local
MAX_VALUE - ca 1.7977E+308
to that function. Local variables are visible to all nested Internal Functions
functions. MIN_VALUE ca 5E-324
decodeURI - reverses encodeURI
Local entities hide globals bearing the same name. NEGATIVE_INFINITY, POSITIVE_INFINITY
decodeURIComponent - reverses encodeURI...
Variable Types n.toExponential(m) n in scientific notation with m
encodeURI encodes everything except
decimal places.
string: var s = 'explainthat' or explainthat :/?&;,~@&=$+=_.*()# and alphanumerics.
n.toFixed() - n rounded to the closest whole number.
number: var n = 3.14159, 100, 0... encodeURIComponent encodes everything except
_.-!~*() and alphaumerics. n.toPrecision(m) n rounded to m figures.
boolean: var flag = false or true
escape hexadecimal string encoding. Does not Hexadecimal numbers are designated with the prefix
object: var d = new Date(); 0x or 0X. e.g. 0xFF is the number 255.
encode +@/_-.* and alphanumerics.
function: var Greet = function sayHello() {alert('Hello')}unescape reverses escape String Object
JavaScript is a weakly typed language i.e. a simple eval evaluates JavaScript expressions length number of characters in the string
assignment is sufficient to change the variable type. The
s.charAt(n) returns s[n]. n starts at 0
typeof keyword can be used to check the current isNaN true if the argument is not a number.
variable type. isFinite isFinite(2/0) returns false s.charCodeAt(n) Unicode value of s[n]
Special Values parseInt - parseInt(31.5) returns 31 s.fromCharCode(n1,n2..) - string built from Unicode
values n1, n2...
The special values false, Infinity, NaN, null, true & parseFloat - parseFloat(31.5) returns 31.5
undefined are recognized. null is an object. Infinity s1.indexOf(s2,n) location of s2 in s1 starting at
Array Object position n
and NaN are numbers.
length number of elements in the array
Operators s1.lastIndexOf(s2) location of s2 in s1 starting from
concat concatenates argument, returns new array. the end
Operator Example Result
join returns elements as a string separated by s.substr(n1,n2) returns substring starting from n1 upto
+ 3+2 5 argument (default is ,) character preceding n2. No n2 = extract till end. n1 < 0 =
'explain' + 'that' explainthat pop suppress & return last element extract from end.
- 3-2 -1 push adds new elements to end of array & returns s.toLowerCase() - returns s in lower case characters
new length. s.toUpperCase() - care to guess?
* 3*2 6
reverse inverts order of array elements
shift suppress & return first element
JavaScript Quick Reference Card1.03

Escape Sequences { alert(num); ownerDocument take a guess


\n - new line, \r - carriage return, \t tab character, num--;} style CSS style declaration
\\ - \ character, \' - apostrophe, \'' - quote } tagName element tag type. Curiously, always in
\uNNNN Unicode character at NNNN uppercase
e.g. \u25BA gives the character function doLoop(num){ textContent the Firefox equivalent of innerText
JavaScript in HTML do{ location Object
External JavaScript alert(num); host URL of the site serving up the document
num--; href the entire URL to the document
<script type=text/javascript defer=defer
src=/scripts/explainthat.js></script> }while (num > 0); pathname the path to the document on the host
Inline JavaScript } protocol the protocol used, e.g. http
<script type=text/javascript> reload(p) - reload the document. From the cache if p is
//your code here function forLoop(num){ true.
</script> replace(url) replace the current document with the
var i;
Comments one at url. Discard document entry in browser history.
for (i=0;i<num;i++){
/* Comments spanning multiple lines */ screen Object
alert(num);
// Simple, single line, comment height screen height in pixels
}
Conditional Execution width screen width in pixels
}
if (Condition) CodeIfTrue;else CodeIfFalse4 window Object
Multiline CodeIf# must be placed in braces, {} alert(msg) displays a dialog with msg
break causes immediate termination of the loop.
switch (variable) clearInterval(id) clears interval id set by setInterval
loop statements after continue are skipped and the next
{ execution of the loop is performed. clearTimeout(id) clears timeout id set by setTimeout
case Value1:Code; confirm(msg) shows a confirmation dialog
break; function forInLoop(){ print() - prints the window contents
case Value2:Code; var s,x; prompt(msg,[default]) shows prompt dialog,
break; optionally with default content. Returns content or null.
for (x in document)
..... setInterval(expr,interval,[args]) sets repeat at
{ interval ms. The function expr is evaluated, optionally
default:Code; s=x + ' = ' + document[x]; with args passed as parameters.
} alert(s); setTimeout(expr,time,[args]) Like setInterval but
variable can be boolean, number, string or even date. non-repeating.
}
(condition)?(CodeIfTrue):(CodeIfFalse) Notes
}
1
Parentheses are not necessary but advisable Evaluates after use 2 Evaluates before use
This code is best tested in Opera which offers the option 3
Error Handling Zero-fill right shift 4 Note the semicolon!
of stopping the script at each alert. In place of
Method 1:The onerror event document any JavaScript object or an array can be Color Coding
used to loop through its properties/elements. italics user code blue JavaScript Keywords
<script type=text/javascript>
return red Option object JavaScript DOM object
function whenError(msg,url,lineNo){
//use parameters to provide meaningful messages return causes immediate termination of the JavaScript green only numeric values blue - object properties
function. If no value is returned, or if return is missing green object methods magenta object events
} the function return type is undefined.
window.onerror = whenError Tested with Internet Explorer 6+, Firefox 1.5+ & Opera
document Object 9.1+.
</script> body - the body of the document
If you find this reference card useful please help us by
Place this code in a separate <script>..</script> tag cookie - read/write the document cookies
creating links to our site http://www.explainth.at where
pair to trap errors occurring in other scripts. This
you will find other quick reference cards and many other
technique blocks errors without taking corrective action. domain where was the document served from?
free programming resources.
forms[] - array of all forms in the document
images[] - array of all images in the document
Method 2:The try..catch..finally statement
referrer who pointed to this document?
function showLogValue(num){
URL the URL for the document
var s = 'No Error';
getElementById(id) element bearing ID of id
try
getElementsByName(n) array of elements named n
{if (num < 0) throw 'badnum';
getElementsByTagName(t) - array of t tagged
if (num == 0) throw 'zero'; }
elements
catch (err)
write write plain or HTML text to the document
{ s = err;
onload occurs when the document is loaded
switch (err) {
onunload occurs when user browses away, tab is
case 'badnum':num = -num; closed etc.
break; Element Object
case 'zero':num = 1; By element we mean any HTML element retrieved using
break; } the document.getElementBy# methods.
} attributes all element attributes in an array
[finally{ alert([s,Math.log(num)]);}] className the CSS style assigned to the element
} id the id assigned to the element
The finally block is optional. The two techniques can be innerHTML HTML content of the element
used in concert. innerText content of the element shorn of all HTML
Looping tags. Does not work in Firefox
function whileLoop(num){ offset# element dimensions (# = Height/Width) or
while (num > 0) location(# = Left/Right) in pixels

You might also like