<!--include one of the following at the beginning of your doc to force IE6+ into standards mode--> <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0//EN"> <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Strict//EN"> <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> <head> <meta http-equiv="Content-Script-Type" content="text/javascript"> <!--set default script type--> <script src="path/util.js"></script> <!--external file--> <script src="path/util.js type="text/javascript" language="JavaScript"></script> <script>//javascript goes here<script> <!--embedded version simple--> <script type="text/javascript" language="JavaScript"> <!--embedded version descriptive--> // JavaScript goes here <!--future will be--> </script> <!--type="application/javascript"--> <script><![CDATA[ <!--XHTML ver of script tag--> // JavaScript goes here ]]></script> <script defer><!--JavaScript here--></script> <!--IE runs script at end of doc--> <script defer="defer"><!--JavaScript here--></script> <!--XHTML version of the same--> <!--attach event handler to DOMContentLoaded--> <!--firefox defer technique (undocumented)--> <script><!-- Old browsers don't recognize <script> tags // use html comments above to hide Javascript here // No longer needed --></script> </head> <body> <noscript> This displays if JavaScript has been disabled. </noscript> ... <script> // single-line comment /* multi line comment */ var num=1; // comment after the line for(i = 1; i < 10; i++) { num = num + num; document.write("i: " + i + ", num: " + num + "<br />"); } document.write("you may have to write </" + "script> or maybe </script>"); </script> ... </body>
12, 1.2, "hello world", 'Hi', true, false, /blah/gi (regular expression for patern matching), null { a:5, b:2 } - object initializer [1,2,3,4,5] - array initializer
Infinity | When floating point value gets larger then largest representable finite number |
NaN | (Not-a-Number) - Undefined result or an error |
Number.MAX_VALUE | |
Number.MIN_VALUE | |
Number.NaN | |
Number.POSITIVE_INFINITY | |
Number.NEGATIVE_INFINITY | |
null | variable does not conatain a valid object, array, nujmber, string, or boolean value. Converts to false in a boolean context. Converts to "null" in a string context. Converts to 0 in a numeric context. |
undefined | a var that has been declared but has no value assigned to it, or an object property that does not exist. You can also get the undefined value using the void operator. Equality operator (==) says it is equal to null. Identity operator (===) does not. |
\0 | The NUL character |
\b | backspace |
\t | horizontal tab |
\n | newline |
\v | vertical tab |
\f | form feed |
\r | carriage return |
\" | double quote |
\' | single quote/apostrophe |
\\ | backslash |
\xXX | char specified by 2 hex digits |
\uXXXX | unicode char specified by 4 hex digits |
\XXX | char specified by 3 octal digits. not supported in ECMAScript v3 |
word = "up" datext = "What's " + word + "?" document.write(datext + "<br />"); document.write(datext.length + "<br />"); lastchar = datext.charAt(datext.length - 1) document.write(lastchar + "<br />"); sub = datext.substring(2,6) document.write(sub + "<br />"); posoffirstlettera = datext.indexOf('a') document.write(posoffirstlettera + "<br />");
lastchar = datext[datext.length - 1]
var n = 100; var s = n + " bottles of beer on the wall."; var nstring = n + ""; var nstring = String(n); //better nstring = n.toString(); var n = 17 document.write(n.toString(2) + " "); // Binary document.write(n.toString(8) + " "); // Octal document.write(n.toString(16) + " "); // Hex
var product = "21" * "2"; document.write(product + "<br />"); var number = "42" - 0; // auto-converts string to num - adding results in string concat var number = Number("3.14");
function multiply(x, y) { return x*y; } function doublesquare(a, b) { function double (x) { return 2*x } //nested function return (double(a) * double(b)); } document.write(multiply(5, 6)); document.write("<br />"); document.write(multiply(3, 2)/multiply(2,2)); document.write("<br />"); document.write(doublesquare(3,4));
function defadd(a, b) { if (!a) a = 2; //assign default val to a if not passed b = b || 3; //assign default val to b if not passed return(a+b); } document.write(defadd(10,20) + "<br />"); document.write(defadd(10) + "<br />"); document.write(defadd() + "<br />"); document.write(defadd(undefined,20) + "<br />"); document.write(defadd(null,21) + "<br />");
function addemall(x) { var m = 0; document.write("changing " + x); x = x + 1; arguments[0] = arguments[0] + 1; document.write(" to " + x + "<br />"); for (var i = 0; i < arguments.length; i++) m = m + arguments[i]; return m; } function writethevars() { var datype; for(var i=0; i < arguments.length; i++) { datype = typeof arguments[i]; document.write("arg " + i + " is of type " + datype); document.write(" with a value of " + arguments[i] + "<br />"); } } document.write(addemall(10,20,2) + "<br />"); writethevars(333,"balloons",true);
function multdown(y) { if (y <= 1) return 1; return y * arguments.callee(y-1); // callee function refers to function being executed } document.write(multdown(4));
function damaththing(args) { args.x = args.x || 3; args.y = args.y || 2; return (args.x + args.y); } document.write(damaththing({x: 5, y: 6}) + "<br />"); document.write(damaththing({y: 20}));
function addit(x,y) { return x+y }; function subit(x,y) { return x-y }; function oper(daoper, arg1, arg2) { return daoper(arg1, arg2) } function oper(daoper, arg1, arg2) { return daoper(arg1, arg2) } document.write(oper(addit,"hi ","there ")); document.write(oper(subit,7,4)); //------------------ var obj1 = { write: function(a) { document.write("<br />this is a "+ a + "<br />"); }, add: function(b,c) { return b + c; } } function callobj1(dafunc,arg1,arg2) { return(obj1[dafunc](arg1,arg2)); } obj1.write("function in a object"); document.write(callobj1("add",5,11));
var double = { var1: 2, compute: function(daval) { this.result = daval * this.var1; } }; double.compute(4); document.write(double.result);
function.length | returns the number of parameters the function expects to be passed (i.e. what's declared) |
function.prototype | Is this part of the prototype for this function |
increment.counter = 0; function increment() { document.write(increment.counter++); // global function var/property kept document.write("<br />"); } increment(); increment(); increment();
var f = new Function("x", "y", "return x*y;") is the same as function f(x, y) { return x*y; }
function f22(x, y) {return x*y;} //document.write(f22.call(o, 1, 2)); document.write(f22.call(o, 1, 2) + "<br />"); document.write(f22.apply(o, [2,2]) + "<br />"); // same as var o = {x:4, y:5}; o.m = f22; document.write(o.m(3,2)); delete o.m;
(function() { // this function has no name var v = 1; document.write("v = " + v); })(); //parens around function invokes is
uniqueID = (function() { if (!_id) var _id = 0; return function() { return _id++; }; })(); document.write(uniqueID() + "<br />"); document.write(uniqueID() + "<br />"); document.write(uniqueID._id);
var blah = new Object(); blah.x = 5; blah.y = 6 document.write(blah.x+blah.y); var now = new Date(); var pattern = new RegExp("\\sthing\\s", "i"); var blah2 = { x:2, y:6 }; var blah3 = { point1: { x: 2, y: 3 }, point2: { x: 4, y: 5 } } document.write(blah3.point2.x);
var now = new Date(); // creates an object holding current date and time var dadate = new Date(2007, 12, 04); dadate.setFullYear(dadate.getFullYear() + 1); var weekday = dadate.getDay(); document.write("The day is "+ now.toLocaleStrint()); //curr date/time
function DispPropNames(obj) { for(var name in obj) document.write(name + ": " + obj[name] + "<br />"); for(i = 1; i < 4; i++) document.write("x" + i + ": " + obj["x" + i] + "<br />"); } var blah77 = {x: "hello", y: "151", z: "goodbye"}; DispPropNames(blah77);
if ("x" in o) o.x = 1; // !== and === distinguish betwen undefined and null. if (o.x !== undefined) o.x = 1; if (o.doSomething) o.doSomething();
var d = new Date(); d.constructor == Date; //Evaluates to true; if ((typeof o == "object") && (o.constructor == Date)) if ((typeof o == "object") && (o instanceof Date))
<pre> <script> function hithere() { document.write("hi there"); } document.write(hithere.toString()); </script> </pre>
toLocalString() | return a localized string representation of the object |
valueOf() | like toSTring(), but converts to primitive, typically a number |
hasOwnProperty() | returns true if not an inherited property |
propertyIsEnumerable | noninherited property, name is a single string, would be enumeriated by a for/in loop.
var blah88 = {x:1, y:2}; if (blah88.propertyIsEnumerable("y") document.write("true<br />"); if (blah88.propertyIsEnumerable("valueOf") document.write("true again<br />"); |
isPrototypeOf() | true if method attached is the prototyp object of the arg |
function Rectangle(w, h) { this.width = w; this.height = h; } //Add after constructor above //this creates a instance method? Rectangle.prototype.area = function() { return this.width * this.height; } //this creates a instance property? Rectangle.prototype.commvar = 1; //this creates a class property Rectangle.uniquevar = 2; //this creates a class method Rectangle.biggerwidth = function(a, b) { if (a.width > b.width) return(a); else return(b); } var r = new Rectangle(3, 4); document.write("r.area - " + r.area() + "<br />"); document.write("r.commvar - " + r.commvar + "<br />"); r.commvar++; document.write("r.commvar - " + r.commvar + "<br />"); var multvar = r.commvar * Rectangle.uniquevar; document.write("multvar - " + multvar + "<br />"); var r2 = new Rectangle(5, 6); var biggerwidthrect = Rectangle.biggerwidth(r, r2); document.write("Rectangle bigger width is " + biggerwidthrect.width + "<br />");
function PositionedRectangle(x, y, w, h) { //grab width and height from before //this is called constructor chaining Rectangle.call(this, w, h) //no grab upper-left corner position this.x = x; this.y = y; } //subclass Rectangle using prototype PositionedRectangle.prototype = new Rectangle(); //delete the width and height properties from the inherited prototype? delete PositionedRectangle.prototype.width; delete PositionedRectangle.prototype.height; //add a method to our subclass PositionedRectangle.prototype.contains = function(x,y) { return (x > this.x && x < this.x + this.width && y > this.y && y < this.y + this.height); } //try out the code var rr = new PositionedRectangle(2,3,4,5); document.write(rr.contains(3,3) + "<br />"); document.write(rr.area() + "<br />"); document.write(rr.x + ", " + rr.y + ", " + rr.width + ", " + rr.height + "<br />"); document.write(rr instanceof PositionedRectangle && rr instanceof Rectangle && rr instanceof Object); document.write("<br />");
//store a ref to superclass constructor PositionedRectangle.prototype.superclass = Rectangle; function PositionedRectangle(x, y, w, h) { this.superclass(w,h); this.x = x; this.y = y; }
// if Rectangle had a toString method defined Rectangle.prototype.toString = function() { return "[" + this.width + "," + this.height + "]"; } //and you wanted to override and still augment/call the method from within PositionedRectangle.prototype.toString = function() { return "(" + this.x + "," + this.y + ") " + Rectangle.prototype.toString.apply(this); // OR if you've defined the superclass above... //return "(" + this.x + "," + this.y + ") " + // this.superclass.prototype.toString.apply(this); }
var zz = new Array(); zz[0] = 5.4; zz[1] = "sleeping"; zz[2] = true; zz[3] = { x: 3, y: 2 }; var yy = new Array(9.8, "snoring", false, { x: 7, y: 6 }); document.write(zz[0] + " " + yy[1] + "<br />"); document.write("zz.length = " + zz.length + "<br />); var matrix = [[9,8,7],[6,5,4],[3,2,1]]; document.write(matrix[1][2]); // array indexes start at 0 new xx = new Array(10); // 10 undefined elements new ww = [6,,,,2]; // 3 empty elements in this one var daarray = new Array(3); // length defined. elements at this point are undefined var veggies = ["carrots", "peas", "broccoli"] for(var ii = 0; ii < veggies.length; ii++) document.write(veggies[ii] + "<br />"); document.write(typeof veggies);
var blah = [ 'first entry', 'second entry' ]; blah.push('third entry'); blah[links.length] = 'fourth entry'); // also pushes length to be one more...
Array.shift() | deletes first element |
Array.pop() | deletes last element |
Array.splice() | deletes contiguous range of elements from array |
join() Array.join(", ") //optional specify separator | returns all elements of array as a concatenated string |
reverse() Array.reverse() | reverses te order of the elements of the array |
sort()a.sort(function(a,b) { if ((a.substring(0,0) == "A") && (b.substring(0,0) != "A")) return(-1); // anything w/ "A" goes to beginning else return(0); // otherwise don't sort it }); |
|
concat() Array.concat(<elements>) Array.concat(4,5) |
|
slice() Array.slice(<slice range>) Array.slice(4,5) |
|
splice() Array.splice(<beginning position>, [<number of elements>],[<arg1 to insert>,<arg2 to insert>,...]) var ab = [10,20,30,40,50,60,70,80]; bb = ab.splice(5); document.write("bb - " + bb + ", ab - " + ab + "<br />"); bb = ab.splice(1,2); document.write("bb - " + bb + ", ab - " + ab + "<br />"); bb = ab.splice(2,0,95,96); document.write("bb - " + bb + ", ab - " + ab + "<br />"); bb = ab.splice(2,2,[97,98],99); document.write("bb - " + bb + ", ab - " + ab + "<br />"); |
|
push(), pop() Array.push(<element(s)>) Array.pop([<numberofelements>]) | push or pop elements onto the end of the array like a stack |
unshift(), shift() | like push() and pop(), but puts stuff on beginning of array |
toString(), toLocalString() | comma separated list |
var scope1 = "global"; var scope2 = "global"; function changescope() { scope1 = "local"; //just changed the global var scope1 var scope2 = "local"; //only changing the local var scope2 document.write("inside function<br />"); document.write("scope1 - " + scope1 + " "); document.write("scope2 - " + scope2 + " " + "<br />"); } changescope(); document.write("outside function<br />"); document.write("scope1 - " + scope1 + " "); document.write("scope2 - " + scope2 + " ");
<< | left shift |
>> | right shift with sign extension |
>>> | Right shift with zero extension |
instanceof | Check object type
var d = new Date();
d instanceof Date; // true d instanceof Number; //false |
in | Check whether property exists. Left-side operand is or can be converted to a string. right-side operand that is an object or array.
var dot = { x:1, y:2 };
var davalue = "x" in point; // evaluates to true var daothervalue = "z" in point; //evaluates to false; there is no z property |
== | Tests for equality |
!= | Tests for inequality |
=== | Tests for identity |
!== | Tests for non-identity |
?: | Conditional operator (3 operands) (example x > 0 ? x*y : -x*y) |
, | Multiple evaluation (x = 0, y = 1, z = 2 |
^ | bitwise XOR |
~ | bitwise NOT (unary) |
! | logical complement (unary) |
delete | undefine a property (unary)
var xyz = {x:1, y:2};
delete xyz.x; // delete one of the object properties delete xyz; // can't delete declared vars only var/object properties x = 1; // implicit declaration delete x; // this will work var dadate = new object(); dadate.date1 = new Date(); dadate.date2 = dadate.date1; delete dadate.date1; // delete property date1 document.write(dadate.date2); // this will work because the object still exists |
void | return undefined value (unary) (Example <a href="javascript:void window.open();">Open New Window</a>) |
typeof | Return datatype (unary). Evaluates to number, string, boolean, function, undefined, or object (for objects, arrays, and null). |
Statement | Syntax | Purpose |
---|---|---|
break | break; break label | |
case | case expression: | within a switch statement |
continue | continue; continue label; | restart innermost loop or or loop named label |
default | default: | default statement in a switch statement |
do/while | do statement while (expression); | |
empty | ; | do nothing |
for | for (initialize ; test ; increment) statement | |
for/in | for (variable in object) statement | loop through object properties |
function | function funcname([arg1[..., argn]]) { statements } | function declaration |
if/else | if (expression) statement1 [else statement2] | |
label | identifier: statement | give statement the name identifier |
return | return[expression]; | exit a function possibly with the value expression |
switch | switch (expression) { statements } | multiway branch to statements labeled with case or default: |
throw | throw expression; | Throw an exception |
try | try { statements }catch (identifier) { statements }finally { statements } | catch an exception |
var | var name_1 [ = value_1] [ ,..., name_n [ = value_n]]; | declare and init vars |
while | while (expression) statement | |
with | with (object) statement | extend scope chain (deprecated) |
var Class = {}; Class.blah = function(a) { document.write(a) }; Class.blah2 = function(a) { var b = 1; document.write(a+b); } Class.blah("hi there "); Class.blah2(2);
//throw errors if each lvl exists but is not an object var com; if (!com) com = {}; else if (typeof com != "Object") throw new Error("com already exists and is not an object"); if (!com.mydomain) com.mydomain = {}; else if (typeof com.mydomain != "Object") throw new Error("com.mydomain already exists and is not an object"); if (com.mydomain.Daclass) throw new Error("com.mydomain.daclass already exists"); //now define it com.mydomain.Daclass = { blah: function(z) { document.write(z); }, blah2: function(z) { var y = 1; document.write(z+y); } }; com.mydomain.Daclass.blah("hello there "); com.mydomain.Daclass.blah2(4);
var com; if (!com || !com.mydomain || !com.mydomain.daclass) throw new Error("com/mydomain/Daclass.js has not been loaded");
specialclass = { init: function() { this.var1 = "well hello"; }, checkinit: function() { document.write(this.var1); } }; (function() { //anonymous function specialclass.init(); })(); specialclass.checkinit();
var pattern = /s$/; //look for something that ends with s var pattern = new RegExp("s$"); /[abc]/ //matches any one of the letters a, b, c /[^abc]/ //matches any one char other then a, b, c /[a-z]/ //match any lowercase letter or digit in the latin alphabet
String | search() | returns char position of start of matching substring or -1 if no match "Blahtext".search(/text/i) returns 4 |
replace() | matches 1st argument, and replaces with second argumentvar datext="Blahtext is something that blahtext can't stand"; var datext2 = datext.replace(/Blahtext/gi,"BlahText"); //replaces all instances of blahtext with capitalized document.write(datext + "<br />"); document.write(datext2 + "<br />"); | |
match() | matches arguments and returns them into an array.
var daarray99 = "4 and 20 blackbirds backed 36 pies".match(/\d+/g); for (i = 0; i < daarray99.length; i++) document.write(daarray99[i] + "<br />"); var url = /(\w+):\/\/([\w.]+)\/(\S*)/; var daarray100 = "http://dhtmlsite.com/ajax.php".match(url); for (i = 0; i < daarray100.length; i++) document.write(daarray100[i] + "<br />"); | |
split() | breaks string into array of strings around delimiter
var daarray101 = "abc, def,geh ,ikj , lmn".split(/\s*,\s*/); for (i = 0; i < daarray101.length; i++) document.write(daarray101[i] + "-"); | |
RegExp | exec() | like string match above, except it always returns a single match. With the g flag set, .lastIndex is char pos following the matched substring (so you can rerun the match from there). .lastIndex goes to 0 when no more matches are found a9or you can set it to quit the search early).var text102 = "blah2 is after blah or the initial blah0"; var pattern102 = /blah\d*/g; var result102 = pattern102.exec(text102); document.write(result102 + " - " + pattern102.lastIndex); var result102 = pattern102.exec(text102); document.write(" - " + result102 + " - " + pattern102.lastIndex); |
test() | returns true if string contains a match for reg expression. Uses .lastIndex the same way as exec()var pattern103 = /blah/i; document.write(pattern103.test("this blah text"); |
Char | Matches |
---|---|
Alphanumeric char | itself |
\0 | The NUL char (\u0000) |
\t | Tab (\u0009) |
\n | Newline (\u000A) |
\v | Vertical tab (\u000B) |
\f | Form feed (\u000C) |
\r | Carriage Return (\u000D) |
\xnn | Latin char specified by hex # |
\uxxxx | Unicode char specified by hex number |
\cX | control char (i.e. \cJ is control-j (newline)) |
char | matches |
---|---|
[...] | any one char between brackets |
[^...] | any one char not between brackets |
. | any char except newline or another Unicode line terminator |
\w | [a-zA-Z0-9_] |
\W | [^a-zA-Z0-9_] |
\s | whitespace |
\S | any char that is not whitespace |
\d | [0-9] |
\D | [^0-9] |
[\b] | backspace |
^ | beginning of the string, beginning of a line |
$ | end of the string, end of a line |
\b | word boundary (i.e. between \w and \W, or between \w and beginning or end of string /\bhello\b/ matches hello at the beginning or end of a line, or in the middle of a sentence |
\B | not a word boundary /\Bhello/ matches Wellhello but not hello |
(?=p) | positive lookahead assertion - only matches if exists, but doesn't match /hello(?=:)/ matches 'hello: how to say hi', but doesn't match 'hello - how to say hi' |
(?!p) | negative lookahead assertion - only matches if doesn't exist /hello(?!:)/ doesn't match 'hello: how to say hi', but does match 'hello - how to say hi' |
char | meaning |
---|---|
{n,m} | match previous item n to m times |
{n,} | match previous item n or more times |
{n} | match exactly n occurrences of previous item |
? | {0,1} (i.e. optional) |
+ | {1,} (i.e. one or more) |
* | {0,} (i.e. 0 or more) |
char | meaning |
---|---|
| | match either expression to left OR right |
(...) | group items into single unit, and remember for later references |
(?:...) | group items into single unit, but do not remember for later reference |
\n | match the same item that was matched in group n |
/(ab|cd)/ //matches ab or cd /(['"])([^'"]*)\1/ //matches a string that begins and ends with the same type of quote (' or ") //for ref, /2 matches the string, and the string doesn't have any quotes in it (?:\+|%2B|%2b)(1\d\d\d\d\d\d\d\d\d\d) //match + in any of it's forms but don't remember it //then match a 1 followed by 10 digits (and remember it)